Lesson 9 of 31

Bitwise Operators

Bitwise Operators

Bitwise operators work on individual bits of integer values. They are essential for low-level programming, flags, and performance-critical code.

The Operators

OperatorNameExample
&AND5 & 3 = 1
|OR5 | 3 = 7
^XOR5 ^ 3 = 6
~NOT~5 = -6
<<Left shift1 << 3 = 8
>>Right shift8 >> 2 = 2

The Borg think in binary. "You will be assimilated" -- one bit at a time.

How It Works

Think in binary:

  5 = 0101
  3 = 0011
---------
  & = 0001 (1)   -- both bits must be 1
  | = 0111 (7)   -- either bit can be 1
  ^ = 0110 (6)   -- exactly one bit must be 1

Bit Flags

A common pattern is using individual bits as boolean flags:

#define READ    1   // 001
#define WRITE   2   // 010
#define EXEC    4   // 100

int perms = READ | WRITE;  // 011 = 3
if (perms & READ) {
    printf("Can read\n");
}

Setting, Clearing, and Toggling Bits

int flags = 0;
flags = flags | (1 << 2);   // set bit 2
flags = flags & ~(1 << 2);  // clear bit 2
flags = flags ^ (1 << 2);   // toggle bit 2

Left Shift as Multiply

Shifting left by n is the same as multiplying by 2^n:

int x = 3 << 2;  // 3 * 4 = 12

Your Task

Write a function int count_set_bits(int n) that counts how many bits are set to 1 in the binary representation of n. Use bitwise AND and left shift to check each bit position. Print the result for 0, 7, 255, and 1.

TCC compiler loading...
Loading...
Click "Run" to execute your code.