I'd like to check if a binary number has a '0' or a '1' at a specific position.
example:
if the binary number is: 101000100
checking at position 6 should result in '1'.
etc...
I'm coding in C, so obviously I could use sprintf / scanf and the likes, but I guess there must be something better (read: more time efficient / easier)!
What would be a good mechanism to do this?
This will filter out the bit you're looking for:
number & (1 << position)
If you really need a 1 or 0 response, you can use this to make it a boolean value:
!!(number & (1 << position))
Or even better (thanks Vadim K.):
(number >> position) & 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With