简体   繁体   中英

Java Integer index to bit position

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

You have to use bit shifting operator:

private boolean bitwiseAnding(int val, int indx){
    int mask = 1 << (indx-1);
    return (val & mask) != 0;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM