Bit Manipulation in C

Bitwise Operators

& AND
| OR
^ XOR
~ NOT

Truth Tables

AND (“&”)

truth table

+--------+--------+-----------------+
| bit a  | bit b  | a & b (a AND b) |
+--------+--------+-----------------+
|     0  |     0  |               0 |
|     0  |     1  |               0 |
|     1  |     0  |               0 |
|     1  |     1  |               1 |
+--------+--------+-----------------+

byte example

     11001000  
   & 10111000 
     -------- 
   = 10001000

OR (“|”)

truth table

+--------+--------+----------------+
| bit a  | bit b  | a | b (a OR b) |
+--------+--------+----------------+
|     0  |     0  |              0 |
|     0  |     1  |              1 |
|     1  |     0  |              1 |
|     1  |     1  |              1 |
+--------+--------+----------------+

byte example

     11001000  
   | 10111000 
     -------- 
   = 11111000

XOR (“^”)

truth table

+--------+--------+-----------------+
| bit a  | bit b  | a ^ b (a XOR b) |
+--------+--------+-----------------+
|     0  |     0  |               0 |
|     0  |     1  |               1 |
|     1  |     0  |               1 |
|     1  |     1  |               0 |
+--------+--------+-----------------+

byte example

     11001000  
   ^ 10111000 
     -------- 
   = 01110000

NOT (“~”)

truth table

+--------+----------------------+
| bit a  | ~a (complement of a) |
+--------+----------------------+
|     0  |                    1 |
|     1  |                    0 |
+--------+----------------------+

byte example

   ~ 11001000   
     -------- 
   = 00110111

Shift Operators

>> right shift (8 bits variable)

 0x80>>0 = 0b10000000
 0x80>>1 = 0b01000000
 0x80>>2 = 0b00100000
 0x80>>3 = 0b00010000
 0x80>>4 = 0b00001000
 0x80>>5 = 0b00000100
 0x80>>6 = 0b00000010
 0x80>>7 = 0b00000001

<< left shift (8 bits variable)

 0x01<<0 = 0b00000001
 0x01<<1 = 0b00000010
 0x01<<2 = 0b00000100
 0x01<<3 = 0b00001000
 0x01<<4 = 0b00010000
 0x01<<5 = 0b00100000
 0x01<<6 = 0b01000000
 0x01<<7 = 0b10000000

Examples

# Set a bit
BYTE |= (1 << i);

# Clear a bit
BYTE &= ~(1 << i);

# Toggle a bit
BYTE ^= (1 << i);

# Set bits i and k
BYTE ^= ((1 << i) | (1 << k));

Macros

#define BV(bit)			(1 << (bit))
#define setBit(byte, bit)	(byte |= BV(bit))
#define clearBit(byte, bit)	(byte &= ~BV(bit))
#define toggleBit(byte, bit)	(byte ^= BV(bit))

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading Facebook Comments ...
Loading Disqus Comments ...