To extract a bit from a number in the C programming language, you can use the bitwise AND operator (&) and a bit mask. A bit mask is a binary number with a 1 in the position of the bit you want to extract, and 0s in all other positions. Here’s an example:
// number from which to extract the bit
int num = 10;
// position of the bit to extract (0-based)
int bit_pos = 2;
// create the bit mask by shifting 1 to the left by the bit position
int mask = 1 << bit_pos;
// use the bitwise AND operator to extract the bit
int bit = num & mask;
In this example, the value of bit
will be 0, since the 2nd bit (counting from the right) of the number 10 is 0.
Alternatively, you can use the bitwise right shift operator (>>) to shift the number right by the bit position and then use the bitwise AND operator to extract the bit:
// number from which to extract the bit
int num = 10;
// position of the bit to extract (0-based)
int bit_pos = 2;
// use the bitwise right shift operator to shift the number right by the bit position
int shifted = num >> bit_pos;
// use the bitwise AND operator to extract the bit
int bit = shifted & 1;
In this example, the value of bit
will also be 0.