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


int temp = 0x5E; // in binary 0b1011110.

Is there such a way to check if bit 3 in temp is 1 or 0 without bit shifting and masking.

Just want to know if there is some built in function for this, or am I forced to write one myself.

2/7/2009 1:19:40 PM

Accepted Answer

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.

4/30/2019 12:19:24 PM

Check if bit N (starting from 0) is set:

temp & (1 << N)

There is no builtin function for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow