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

前端 未结 14 1831
抹茶落季
抹茶落季 2020-11-29 01:14

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

14条回答
  •  感动是毒
    2020-11-29 01:41

    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).

提交回复
热议问题