Reputation: 486
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
Upvotes: 1
Views: 1298
Reputation: 22595
You have to use bit shifting operator:
private boolean bitwiseAnding(int val, int indx){
int mask = 1 << (indx-1);
return (val & mask) != 0;
}
Upvotes: 5
Reputation: 140319
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
Upvotes: 5