Bit Masking
Bit Masking
In the C language, the smallest data type available is char, which is 1 byte (8 bits):
[] [] [] [] [] [] [] []
One possibility is to use an entire char to store the single bit. This is wasteful.
Another option is to figure out how to manipulate just one bit within a char, or within any
data type for that matter. In the C language, this is accomplished using bit manipulators.
The bitwise AND operator performs an AND between two values, independently at every
bit. For example:
The bitwise OR operator performs an OR between two values, independently at every bit.
For example:
So what would be the final values of x,y in the following? [have class work it out]
char x,y;
x=17; /* first put the value into binary; 17 = 00010001 */
y=16; /* 16 = 00010000 */
x=x&y; /* x=16 */
y=x|4; /* y=20 */
The bitwise shift operators move the bits left or right the given amount. The left shift
adds in new low-order bits, setting them all to zero. The right shift adds in new high-
order bits, setting them equal to the value of the original highest order bit. For example:
So what would be the final values of x,y in the following? [have class work it]
char x,y;
x=17; /* first put the value into binary; 17 = 00010001 */
y=16; /* 16 = 00010000 */
x=x>>3; /* x=2 */
y=y<<1; /* y=32 */
Bit masking is the art of using bitwise operators to manipulate individual bits within
larger data types. Here are a few basic manipulations:
Operation Formula
Set Nth bit x = x | 2N
Clear Nth bit x = x & (2T-1-2N), where T=total bits
Read Nth bit (x & 2N) >> N
char x,y;
x=16; /* 00010000 */
x=x|4; /* 00010100 */ /* set 3rd bit */
x=x & (255-16); /* 00000100 */ /* clear 5th bit */
y=(x & 4)>>2; /* 00000001 */ /* read 3rd bit */