Verifying Bit Status Without Shifting or Masking
When manipulating bits, it's often necessary to check the status of a specific bit within an integer variable. Consider the following example:
int temp = 0x5E; // in binary 0b1011110
We want to determine if bit 3 in the binary representation of temp is set to 1 or 0.
Builtin Function?
The question arises: is there a built-in function that performs this operation without resorting to bit shifting and masking?
Custom Macro in C
In C, there is no native solution. However, you can create a macro to simplify the process:
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
where var is the integer to be checked and pos is the bit position (0-indexed, starting from the rightmost bit).
To check the 3rd bit from the right end:
CHECK_BIT(temp, 2)
Std::bitset in C
In C , you can leverage the std::bitset class:
std::bitset<32> bits(temp); if (bits.test(3)) { // Bit 3 is set }
Here, bits represents the binary representation of temp and bits.test(3) checks the value of the 3rd bit.
The above is the detailed content of How to Check a Bit\'s Status Without Shifting or Masking?. For more information, please follow other related articles on the PHP Chinese website!