+ 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

25th Apr 2023, 2:48 AM
Bob
4 odpowiedzi
+ 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
25th Apr 2023, 6:53 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 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.
25th Apr 2023, 2:25 PM
Brian
Brian - avatar
+ 2
You're welcome :)
25th Apr 2023, 1:34 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Yeah, that's what I meant. And thank you
25th Apr 2023, 12:43 PM
Bob