Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a binary number has a '0' or a '1' at a specific position

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 zero (that is at the rightmost '0') should result in '0'.
  • checking at position 2 should result in '1'.
  • checking at position 3 should result in '0'.
  • 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?

like image 918
mike Avatar asked Nov 27 '22 20:11

mike


1 Answers

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
like image 191
Wim Avatar answered Nov 29 '22 10:11

Wim