2

I have a number of type int. It lies within [0,255]. That is, includes 8 bits. I need to check often say:

2(int) = 00000010(Binary)

  1. The bit 6 and bit 7 must be equal to 0 and 1 respectively. 
  And I check it like this:
if ((!(informationOctet_ & (1 << 6))) && (informationOctet_ & (1 << 7)))
{
    ...
}

But it is not very readable, whether it is possible - to do something "beautiful"? I can not use the std::bitset, my head says it's a waste of resources and you can not do without it.

Tipok
  • 675
  • 8
  • 26

2 Answers2

3

There are two reasonable solutions: either set all don't-care bits to zero, and then test the result, or set the don't-care bits to one and test the result:

(x & 0xC0) == 0x80
(x | ~0xC0) == ~0x40

As harold pointed out in the comment, the first form is far more common. This pattern is so common that the optimizer of your compiler will recognize it.

Other forms exist, but they're obscure: ((x ^ 0x80) & 0xC0 == 0) works just as well but is less clear. Some ISA's cannot load large constants directly, so they use the equivalent of ((x>>6) & 0x3) == 0x2. Don't bother with this, your optimizer will.

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

You can apply some masking techniques as,

int i = 246; // Lets say any value.
int chk = ( i & 00000110b ); // eliminates all other bits except 6th & 7th bit
if (chk == 2) // because we want to check 6th bit is 0 & 7th is 1, that becomes 2 value in decimal
    printf("The 6th bit is 0 & 7th bit is 1");
else
    printf("Either 6th bit is not 0 or 7th bit is not 1, or both are not 0 & 1 respectivly");
Waqas Shabbir
  • 755
  • 1
  • 14
  • 34
  • 2
    Usually bits are numbered LSB (0) to MSB (7). Also, binary literals are c++14 as far as I remember [context](http://stackoverflow.com/q/16334024/85371) – sehe Jan 30 '15 at 10:08
  • 1
    Similarly if you say that bits are numbered from 0 to 7. Then by changing the mask to 00000011b & comparing the result with 1 in decimal, you can also find out your answer as well. But the technique was same. – Waqas Shabbir Jan 30 '15 at 10:12
  • 1
    @WaqasShabbir: MSB means **most** significant bit, the leftmost. `0b00000011` has the rightmost, LSB set, and that's bit 0. – MSalters Jan 30 '15 at 10:14