Checking If a Bit Is Set or Not

Checking if bit is not set

When you write if(value & 4), C checks the result to be non-zero. Essentially, it means

if((value & 4) != 0) {

Therefore, if you would like to check that the bit is not set, compare the result for equality to zero:

if((value & 4) == 0) {

C/C++ check if one bit is set in, i.e. int variable

In C, if you want to hide bit manipulation, you can write a macro:

#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))

and use it this way to check the nth bit from the right end:

CHECK_BIT(temp, n - 1)

In C++, you can use std::bitset.

Checking if a bit is set or not

sounds a bit like homework, but:

bool IsBitSet(byte b, int pos)
return (b & (1 << pos)) != 0;

pos 0 is least significant bit, pos 7 is most.

How to check if exactly one bit is set in an int?

So you want to know if a number is power of 2 or not? Well there is a famous algorithm for that, you can simply do,

check_bit(std::uint32_t bits)
return bits && !(bits & (bits-1));

Any power of 2 when subtracted by 1 is all 1s. e.g,

4 - 1 = 3 (011)
8 - 1 = 7 (0111)

The bitwise and of any power of 2 and any number 1 less than it will give 0. So we can verify if a number is power of 2 or not by using the expression, n&(n-1).

It will fail when n=0, so we have to add an extra and condition.

For finding the position of bit, you can do:

int findSetBit(std::uint32_t bits)
if (!(bits && !(bits & (bits-1))))
return 0;
return log2(bits) + 1;

Extra Stuffs

In gcc, you can use __builtin_popcount(), to find the count of set bits in any number.

#include <iostream>

int main()
std::cout << __builtin_popcount (4) << "\n";
std::cout << __builtin_popcount (3) << "\n";

return 0;

Then check if count is equal to 1 or not.

Regarding count, there is another famous algorithm, Brian Kernighan’s Algorithm. Google it up, it finds count in log(n) time.

How can I check that a bit is set (without bitwise operation)?

The 'bit' (actually any base) value of an indexed number index in a value val in base base can in general be calculated as

val = 1966;
index = 2;
base = 10;
alert (Math.floor(val/Math.pow(base,index)) % base);

result: 9

val = 44;
index = 3;
base = 2;
alert (Math.floor(val/Math.pow(base,index)) % base);

result: 1 (only 0 and 1 are possible here – the range will always be 0..base-1).

The combination of Math.floor (to coerce to an integer in Javascript) and Math.pow is kind of iffy here. Even in integer range, Math.pow may generate a floating point number slightly below the expected 'whole' number. Perhaps it is safer to always add a small constant:

alert (Math.floor(0.1+val/Math.pow(base,index)) % base);

Why is a bit-wise AND necessary to check if a bit is set?

(mask >> i) cannot eliminate the higher bits.

For example, when mask = 5 (101 in binary) and i = 1, the value of (mask >> i) is 2. This evaluated as true, but the 2nd lowest bit is 0, so you fail to check the bit correctly.

Therefore, & 1 is necessary to eliminate the higher bits and check one specified bit correctly.

Check if multiple bits are set or cleared

To check whether multiple bits are cleared, you'd typically use this somewhat more concise idiom:

if ((statusRegister & 0x00000102) == 0) {}
// or
if (!(statusRegister & 0x00000102)) {}

You could also check whether multiple bits are set with:

if ((statusRegister | ~0x00000102) == ~0) {}
// or
if (!(~statusRegister & 0x00000102)) {}

But the version in your question is much more common. ANDing with a bitmask is the simplest mental model and easiest to understand for your fellow programmers.

Flags - Check if bits are set and only those bits are set

Sometimes the simplest answer eludes you after having your mind wrapped in complicated things.

This is enough:

if(value == flag)

And if you need to check multiple flags:

if(value == (SOMEFLAG_1 | SOMEFLAG_4))
^ ^
important important

And don't forget to enclose the bitwise operations in parenthesis. The precedence is unexpected and without them value == SOMEFLAG_1 would be evaluated first.

And I guess this is a perfect time for preaching for enabling (and paying attention to) compiler warnings:

clang has a very helpful one -Wparentheses which is included in -Wall:

5 : :5:28: warning: | has lower precedence than ==; == will be
evaluated first [-Wparentheses]

if(value == SOMEFLAG_1 | SOMEFLAG_4)

5 : :5:28: note: place parentheses around the '==' expression
to silence this warning

if(value == SOMEFLAG_1 | SOMEFLAG_4)
( )

5 : :5:28: note: place parentheses around the | expression to
evaluate it first

if(value == SOMEFLAG_1 | SOMEFLAG_4)
( )

gcc has it also:

5 : :5:14: warning: suggest parentheses around comparison in
operand of '|' [-Wparentheses]

 if(value == SOMEFLAG_1 | SOMEFLAG_4)

Related Topics

Leave a reply