Beetwise

Bitwise operators in C and C++

C has six bitwise operators: AND, OR, XOR, NOT and the two shifts.

Each one works on every bit of an integer type.

The logical operators && and || are different operators with different results.

Try bitwise operators in C in the bit editor

The mask 1 << 3, which is bit 3. Edit the expression or select a bit to flip it.

7
6
5
4
3
2
1
0
8
value · 8 bits · unsigned
hex
0x08
Shift

The bitwise operators of C and C++

The bitwise operators of C and C++
OperatorNameIdiomEffect
&ANDx & maskKeep the bits of the mask
|ORx |= maskSet the bits of the mask
^XORx ^= maskToggle the bits of the mask
~NOTx & ~maskClear the bits of the mask
<<Left shift1u << nBuild a mask for bit n
>>Right shiftx >> nMove bit n down to bit 0
&Testif (x & mask)True when a bit of the mask has the value 1

Where bitwise operators in C is used

A register of a microcontroller needs these operators for every field.

A flag word packs many boolean values into one integer.

An embedded codebase uses these idioms more than it uses arithmetic.

Bitwise operators in C: points to note

  • C leaves a shift of a signed negative value undefined. Shift an unsigned type.
  • C leaves a shift by the width of the type or more undefined. A shift of a 32-bit value by 32 is not 0.
  • The right shift of a signed negative value keeps the sign on most targets, so it does not divide as expected.
  • Write 1u << 31 rather than 1 << 31. The literal 1 is a signed int, and the shift overflows it.
  • The operator & has lower precedence than ==, so write (x & mask) != 0 with the parentheses.

The full bit editor

The full editor holds many values, evaluates expressions across them, and reads live values from a serial port.

Open this value in the full editor

Questions about bitwise operators in C

How do I set one bit in C?
Apply x |= (1u << n). The other bits keep their value.
How do I clear one bit in C?
Apply x &= ~(1u << n). The NOT builds a mask with a single 0.
What is the difference between & and &&?
The operator & works on every bit and gives an integer. The operator && gives 0 or 1 and stops at the first false operand.