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

前端 未结 14 1810
抹茶落季
抹茶落季 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:44

    You can also use

    bool isSet = ((value>>x) & 1) != 0;
    

    EDIT: the difference between "(value>>x) & 1" and "value & (1<" relies on the behavior when x is greater than the size of the type of "value" (32 in your case).

    In that particular case, with "(value>>x) & 1" you will have the sign of value, whereas you get a 0 with "value & (1<" (it is sometimes useful to get the bit sign if x is too large).

    If you prefer to have a 0 in that case, you can use the ">>>" operator, instead if ">>"

    So, "((value>>>x) & 1) != 0" and "(value & (1<" are completely equivalent

提交回复
热议问题