Java: Checking if a bit is 0 or 1 in a long

2019-01-06 12:01发布

What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?

14条回答
倾城 Initia
2楼-- · 2019-01-06 12:10

Bit shifting right by x and checking the lowest bit.

查看更多
Juvenile、少年°
3楼-- · 2019-01-06 12:11

Another alternative:

if (BigInteger.valueOf(value).testBit(x)) {
    // ...
}
查看更多
小情绪 Triste *
4楼-- · 2019-01-06 12:13
成全新的幸福
5楼-- · 2019-01-06 12:13

If someone is not very comfortable with bitwise operators, then below code can be tried to programatically decide it. There are two ways.

1) Use java language functionality to get the binary format string and then check character at specific position

2) Keep dividing by 2 and decide the bit value at certain position.

public static void main(String[] args) {
    Integer n =1000;
    String binaryFormat =  Integer.toString(n, 2);
    int binaryFormatLength = binaryFormat.length();
    System.out.println("binaryFormat="+binaryFormat);
    for(int i = 1;i<10;i++){
        System.out.println("isBitSet("+n+","+i+")"+isBitSet(n,i));
        System.out.println((binaryFormatLength>=i && binaryFormat.charAt(binaryFormatLength-i)=='1'));
    }

}

public static boolean isBitSet(int number, int position){
    int currPos =1;
    int temp = number;
    while(number!=0 && currPos<= position){
        if(temp%2 == 1 && currPos == position)
            return true;
        else{
            temp = temp/2;
            currPos ++;
        }
    }
    return false;
}

Output

binaryFormat=1111101000
isBitSet(1000,1)false
false
isBitSet(1000,2)false
false
isBitSet(1000,3)false
false
isBitSet(1000,4)true
true
isBitSet(1000,5)false
false
isBitSet(1000,6)true
true
isBitSet(1000,7)true
true
isBitSet(1000,8)true
true
isBitSet(1000,9)true
true
查看更多
\"骚年 ilove
6楼-- · 2019-01-06 12:14

In Java the following works fine:

if (value << ~x < 0) {
   // xth bit set
} else {
   // xth bit not set
}

value and x can be int or long (and don't need to be the same).

Word of caution for non-Java programmers: the preceding expression works in Java because in that language the bit shift operators apply only to the 5 (or 6, in case of long) lowest bits of the right hand side operand. This implicitly translates the expression to value << (~x & 31) (or value << (~x & 63) if value is long).

Javascript: it also works in javascript (like java, only the lowest 5 bits of shift count are applied). In javascript any number is 32-bit.

Particularly in C, negative shift count invokes undefined behavior, so this test won't necessarily work (though it may, depending on your particular combination of compiler/processor).

查看更多
Explosion°爆炸
7楼-- · 2019-01-06 12:19

I'd use:

if ((value & (1L << x)) != 0)
{
   // The bit was set
}

(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)

查看更多
登录 后发表回答