Check if the binary number has β€œ0” or β€œ1” at a specific position

I want to check if a binary number has "0" or "1" in a specific position.

Example:

if binary number: 101000100

  • checking the zero position (that is, to the far right β€œ0”) should result in '0'.
  • checking position 2 should result in a '1'.
  • check position 3 should be at '0'.
  • a check in position 6 should result in a '1'.

    etc...

I program in C, so obviously I could use sprintf / scanf and the like, but I think there should be something better (read: more time is efficient / easier)!

What would be a good mechanism for this?

+4
source share
3 answers

The bit you are looking for will open:

number & (1 << position) 

If you really need a 1 or 0 answer, you can use it to make it a boolean:

 !!(number & (1 << position)) 

Or even better (thanks to Vadim K. ):

 (number >> position) & 1 
+29
source

This expression evaluates the value of the bit you are looking for, either 0 or 1 :

 (number >> position) & 1 
+30
source

Caution: this code is not compliant. Bjarne Straustrup says , and he should β€œknow that,” β€œObviously it’s illegal to write one member and then read another ...” Nevertheless, I leave this code for educational purposes ...

Here's an alternative that is useful when, say, you read your own binary protocol from a socket:

 #include <cstdlib> union Value { struct { unsigned char a_ : 1; unsigned char b_ : 1; unsigned char c_ : 1; unsigned char d_ : 1; unsigned char e_ : 1; unsigned char f_ : 1; unsigned char g_ : 1; unsigned char h_ : 1; } bits_; unsigned char charVal_; }; int main() { unsigned char someValue = static_cast<unsigned char>(0x42); Value val; val.charVal_ = someValue; bool isBitDSet = val.bits_.d_; return 0; } 
+7
source

All Articles