BETA Try the new lesson view
Code

Bits in a program

Bit operations are best seen as bits. The second program prints every result as 8 bits.

CMakeLists.txt gets one more line:

add_executable(p08_bits bits.c)

bits.c:

  • void show_bits(unsigned int x) prints the 8 lowest bits from the highest: (x >> i) & 1u shifts bit i to the start and keeps only it. After them come = and the value.
  • main with a = 12 and b = 10 shows &, |, ^, ~, << and >>. ~a flips all 32 bits, so & 0xFFu keeps only the lowest 8.
  • Permissions with the masks READ, WRITE, EXECUTE: switch two on, test one, switch one off, toggle the third.

Run it

p08_bits and ▶:

a        00001100 = 12
b        00001010 = 10
a & b    00001000 = 8
a | b    00001110 = 14
a ^ b    00000110 = 6
~a       11110011 = 243
a << 1   00011000 = 24
a >> 2   00000011 = 3
perms    00000011 = 3
Writing allowed.
perms    00000001 = 1
Writing no longer allowed.
perms    00000101 = 5

Compare the columns: a & b has a 1 only where both the a row and the b row have a 1. a << 1 is the same bits one step to the left, so the value doubles.

Commit: Add bit operations.