1

I'm trying to make a dynamic method to check a number through binary anding. I've tried a variety of different approaches but just can't wrap my head around it.

what I need is a method that converts an integer index position and returns a boolean.

private boolean bitwiseAnding(int val, int indx){
    //TODO Convert indx to a bitmask here
    return (val & bitmask)==1;
}

for example:

1 = 0x01
2 = 0x02
3 = 0x04
4 = 0x08
and so on
Simon Jensen
  • 488
  • 1
  • 3
  • 19

2 Answers2

5

You have to use bit shifting operator:

private boolean bitwiseAnding(int val, int indx){
    int mask = 1 << (indx-1);
    return (val & mask) != 0;
}
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
5

Just use bit shifting:

int bitmask = 1 << (indx-1);

But note that you'll only get true for ==1 if indx == 1. You might mean:

(val & bitmask) != 0
Andy Turner
  • 137,514
  • 11
  • 162
  • 243