# Checking if a bit is set in a byte

## Recommended Posts

lonewolff    1182
Hi Guys,

Just wondering if there is an easy way to check if a bit is set in a byte.

So, if I wanted to see it bit 5 was set for example?

##### Share on other sites
lonewolff    1182
Thanks guys!

I'll give this a try very shortly

##### Share on other sites
lonewolff    1182

When you AND two values together, every bit that wasn't 1 in *both* values is set to zero. So if you want to check if a certain bit is set, you AND that one bit to a value, and then see if the result is 0 (the bit wasn't present), or if the result is the same what you AND'd.

if( (10110 & 10000) == 10000 )

You can drop the " == mask " part because, in C++, non-zero integers automaticly convert to 'true':
if(value & mask) //If the result is 00000, then the statement evaluates to false, otherwise it evaluates to true.

Hodgeman's func does the same thing, but also uses an index to create the mask by shifting the value 00000001 over N places to become (for example) 00010000.

This actually seems to work very well. Easy to understand too

##### Share on other sites
Pink Horror    2459

if( (10110 & 10000) == 10000 )

I wonder, why do some people write "== mask" instead of "!= 0"? I suppose it doesn't matter much when the variable is "mask" and/or you use a function, but I've seen this pattern with huge blocks of hard-coded if checks with duplicated giant enum names everywhere.

##### Share on other sites
aregee    1072

if( (10110 & 10000) == 10000 )

I wonder, why do some people write "== mask" instead of "!= 0"? I suppose it doesn't matter much when the variable is "mask" and/or you use a function, but I've seen this pattern with huge blocks of hard-coded if checks with duplicated giant enum names everywhere.

Consider what happens if mask contains more than one bit set. Comparing the AND-result against the mask checks if all bits are set, while comparing against 0 checks if any bit is set.

In that case it is not a matter of relative style or convention, but a matter of absolute correctness; one is correct and the other one is wrong.

To me it is also a question about clarity.  When you read the code, it is immediately clear what the intention is when you test against 'mask', rather than wondering for a few seconds why you are testing against 'not equal to zero'.

##### Share on other sites
aregee    1072

To me it is also a question about clarity.  When you read the code, it is immediately clear what the intention is when you test against 'mask', rather than wondering for a few seconds why you are testing against 'not equal to zero'.

It’s not about clarity. Brother Bob is exactly correct. It is about correct functionality of the program.

ui32Mask = 0xF;
if ( (ui32Value & ui32Mask) != 0 ) // Are ANY of the lower 4 bits set?
if ( (ui32Value & ui32Mask) == ui32Mask ) // Are ALL of the lower 4 bits set?

There is nothing about style or clarity—they absolutely do not do the same thing (unless only 1 bit is set in ui32Mask).
It depends purely on whether you want to test for any bits or all bits, and that is essential for the correctness of any algorithm/code/program.

L. Spiro

Where do I say that Brother Bob is wrong?  He is spot on.  I just said that for me it is ALSO about clarity.  Notice the word 'also'.  In the case where you are just testing for one bit, both cases are right, but then you should probably not call it 'mask', but rather call it 'bit'.  OP asked how to test for a bit, but the case with a mask is more generic.

Edit: if it was not clear; I meant that using 'mask' was more clear than using '!= 0'.

Edited by aregee

##### Share on other sites
JoshuaWaring    1359

I do it like this, but I'd have the enum in it's own header to be reused

enum struct BIT{
_1 = 0x1,
_2 = 0x2,
_3 = 0x4,
_4 = 0x8,
_5 = 0x10,
_6 = 0x20,
_7 = 0x40,
_8 = 0x80,
};

int eg = 20;

if(eg & BIT::_5){

}


##### Share on other sites
L. Spiro    25615

I do it like this, but I'd have the enum in it's own header to be reused

enum struct BIT{
_1 = 0x1,
_2 = 0x2,
_3 = 0x4,
_4 = 0x8,
_5 = 0x10,
_6 = 0x20,
_7 = 0x40,
_8 = 0x80,
};

int eg = 20;

if(eg & BIT::_5){

}


You’re still falling short of optimal.

enum BIT{   // “struct” does not belong.
_1 = 1 << 0,
_2 = 1 << 1,
_3 = 1 << 2,
_4 = 1 << 3,
_5 = 1 << 4,
_6 = 1 << 5,
_7 = 1 << 6,
_8 = 1 << 7,
};


L. Spiro Edited by L. Spiro

##### Share on other sites
Ectara    3097

I do it like this, but I'd have the enum in it's own header to be reused

enum struct BIT{
_1 = 0x1,
_2 = 0x2,
_3 = 0x4,
_4 = 0x8,
_5 = 0x10,
_6 = 0x20,
_7 = 0x40,
_8 = 0x80,
};

int eg = 20;

if(eg & BIT::_5){

}


That forces people to be one-indexed for bit enumeration; sometimes, being zero-indexed is easier, when you use that index directly as the number of positions to shift. Or, put another way, if the index is the exponent of 2 for the value represented by the bit at that index.

##### Share on other sites
JoshuaWaring    1359
The strict does belong, it means you must access it with scope operator (BIT::) instead of making everything global.

##### Share on other sites
Kian    239
If you want to use the scope operator (which I endorse), it would be better to do:

struct BIT
{
enum {
_1 = 1 << 0,
_2 = 1 << 1,
_3 = 1 << 2,
_4 = 1 << 3,
_5 = 1 << 4,
_6 = 1 << 5,
_7 = 1 << 6,
_8 = 1 << 7,
};
};

Kian    239

##### Share on other sites
Kian    239
I'm not sure you can use scoped enums (enum class/enum struct) to do bitwise operations, since you can't convert them to int without an explicit cast. If you want to use it as a mask you need to stick a regular enum in a class or struct.

##### Share on other sites
Pink Horror    2459

The whole BIT enum idea is practically pointless once you get binary literals:

You're still going to want to give them names, right? I don't want to have put in a comment explaining what bit "0b001000" is when I could have used something with a name instead. And writing "0b001000" doesn't look any better than writing (1 << 3) to me.

##### Share on other sites
Nypyren    12061

Binary literals will be more useful for multiple bits, I suspect.

##### Share on other sites

The whole BIT enum idea is practically pointless once you get binary literals:

You're still going to want to give them names, right?

Descriptive names for actual flags and masks? Absolutely! But for names like BIT_ONE, BIT_TWO? Probably not. I don't have enums for decimal literals: ONE = 1, TWO = 2, and I don't really see too much of a need for enumerating each bit in an integer, unless the names actually carry meaning.

I don't want to have put in a comment explaining what bit "0b001000" is when I could have used something with a name instead. And writing "0b001000" doesn't look any better than writing (1 << 3) to me.

Aye, that's true: 1 << 3 is relatively compact and clear.

Perhaps digit separators can make it (somewhat) easier to read though: [tt]0b'0010'1000[/tt], especially when multiple bits are set.

(digit separators work with other numeral literals, like floats: [tt]0.123'456'789[/tt], or integers: [tt]1'200'350[/tt])

Unfortunately, unlike binary literals (already available in GCC), I don't think any compiler has digit separators implemented, since they only finally settled on the symbol to use just last month (it'll possibly make it into C++14 with binary literals) - I wish they would've gone with a space instead, but there were too many problems.

You're correct that in actual code, I'd use a descriptively named constant. Magic numbers, regardless of base, are likely to bite later in a project.

I'm just glad binary literals are finally in the standard.

##### Share on other sites
Trienco    2555

Interestingly enough, most people I know who deal with bit fiddling on a daily base don't even really care about binary literals. Using hex numbers is second nature by now and how many people are really going to specify anything beyond 8 bits in a ridiculously long binary representation? In fact, if there are any literals that REALLY need a separator, it's binary ones (it can't get any longer and harder to read than that). I didn't even know those exist and never really missed or needed them, but the first thing about binary literals was "please let me group them, so I won't have to painfully count if it's bit 29 or 30".

Edited by Trienco