+ 2
Check value of a bit
So far my method seems to work, just want to know if there are any edge cases I may not have considered. If I want to check if a particular bit in a binary number is one I would do x & 2^n= 1 where x is the number and n is the index. Assuming a valid value of n
4 Answers
+ 8
I guess you just mistyped:
x & 2^n == 2^n, if the n-th bit is set,
by which you mean,
x & (1 << n) == (1 << n)
I reckon. The 2^n being a hardcoded, named constant.
Alternatively,
(x >> n) & 1 == 1
+ 3
Adding to Ani Jona đ's excellent answer, you may reduce the test by checking for zero, or non-zero.
x & (1 << n) != 0
If the expression is 0, the bit is 0; any other value means that the bit is 1.
+ 2
You're welcome :)
+ 1
Yeah, that's what I meant. And thank you