LOGBOOK

HELP

← again tap: answer good → ↑ swipe up at the end: next

1 / 14
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag

Question

How do bitwise operators work at the bit level in C?

Answer

Bitwise operators (& | ~ ^ << >>) work bit-by-bit on any integer type: AND keeps bits set in both, OR sets bits set in either, XOR sets bits that differ, and NOT flips every bit.

AND, OR, XOR, NOT on bytes

* AND keeps the common 1-bits, OR sets either operand's 1-bits, XOR sets the differing bits, and NOT flips them all — shown on 0x69 and 0x55. *

Operations: & | ~ ^ << >>

NOT (~) - Flip all bits:

~0x41  →  0xBE
~01000001₂  →  10111110₂

~0x00  →  0xFF
~00000000₂  →  11111111₂

AND (&) - Both bits must be 1:

0x69 & 0x55  →  0x41
01101001₂ & 01010101₂  →  01000001₂

OR (|) - Either bit can be 1:

0x69 | 0x55  →  0x7D
01101001₂ | 01010101₂  →  01111101₂

XOR (^) - Exactly one bit must be 1:

0x69 ^ 0x55  →  0x3C
01101001₂ ^ 01010101₂  →  00111100₂

Common uses:

  • Masking: value & 0xFF extracts lowest byte
  • Setting bits: flags | FLAG_BIT
  • Clearing bits: flags & ~FLAG_BIT
  • Toggling bits: flags ^ FLAG_BIT
  • Checking bits: if (flags & FLAG_BIT)

Go deeper:

Bitwise AND of 4-bit integers
Bitwise AND of 4-bit integers
WatchduckYou can name the author as "T. Piesk", "Tilman Piesk" or "Watchduck". · CC BY 4.0 · Wikimedia Commons
or press any other key

Question

How do you flip (invert) all bits in a byte in C?

Answer

Apply ~, which flips every bit (0→1, 1→0) — but watch out: the operand is promoted to int first, so cast back to unsigned char if you want just one byte.

// 01000001
unsigned char b = 0x41;
// 10111110 = 0xBE
unsigned char flipped = ~b;

How it works:

  • ~ flips every bit: 0→1, 1→0
  • Applied to the entire value

Example with binary:

  0x41 = 01000001
 ~0x41 = 10111110 = 0xBE

Watch out for integer promotion:

unsigned char b = 0x41;
// Result is 0xFFFFFFBE (32-bit), not 0xBE!
int result = ~b;
// Cast back: (unsigned char)(~b) = 0xBE
or press any other key