Theory
There is no C syntax for accessing or setting the nth bit of a built-in data type (e.g. a char '). However, you can access the bits using the logical AND operation and set the bits using the logical OR operation.
As an example, let's say that you have a variable that contains 1101, and you want to check the second bit on the left. Just do a logical AND from 0100:
1101 0100 ---- AND 0100
If the result is nonzero, then the second bit must be set; otherwise it has not been established.
If you want to set the third bit on the left, then do a logical OR with 0010:
1101 0010 ---- OR 1111
You can use the C && (for AND) and || (for OR) to complete these tasks. You will need to create bit access patterns (0100 and 0010 in the examples above). The trick is to remember that the least significant bit (LSB) counts 1 s, the next least significant bit is 2 s, then 4 s, etc. Thus, the bit access pattern for the nth low order bit (starting at 0) is simply a 2 ^ n value. The easiest way to calculate this in C is to shift the binary value 0001 (in this example with four bits) to the left by the required number places Since this value is always 1 in unsigned integers, it is simply '1 <n'
Example
unsigned char myVal = 0x65; unsigned char pattern = 1; pattern <<= 3; if(myVal && (char)(1<<3)) {printf("Yes!\n");} myVal |= (char)(1<<7);
This example has not been tested, but should serve as an illustration of a general idea.
Microserf
source share