Bit Operations in C
Introduction
A microcontroller register is a row of bits. One bit turns an LED on, another starts a timer, another reports that a sensor line is high. Bit operations let you change one of those bits and leave the rest alone.
You already know that integers are binary patterns (Data representation). This article is how you set, clear, toggle, and test a single bit, and how a mask selects which bits you mean. Hardware headers are full of these patterns. The macros in C types and macros (BIT, SET_BIT, CLEAR_BIT) are the same idea with a shorter name.
A bit inside an integer
Number the bits from the right, starting at 0. Bit 0 is worth 1, bit 1 is worth 2, bit 3 is worth 8.
1 2 3 4 | |
0b00001010 and 0x0A and 10 are the same value. Hex is the usual way to write a mask in firmware because each hex digit is exactly four bits.
The six bitwise operators
| Operator | Name | What a 1 in the result means |
|---|---|---|
& |
AND | Both bits were 1 |
| |
OR | At least one bit was 1 |
^ |
XOR | The two bits differed |
~ |
NOT | The bit was flipped |
<< |
Left shift | Bits moved toward the high end |
>> |
Right shift | Bits moved toward the low end |
1 2 3 4 | |
So 12 & 10 is 8, 12 | 10 is 14, and 12 ^ 10 is 6.
& and | are bitwise. && and || are logical: they only care whether a whole value is zero or not. value & 0x08 tests a bit. value && 0x08 only asks "are both numbers non-zero?" and throws the bit pattern away.
In plain terms
A mask is a stencil. You hold it over the integer and the holes show the bits you care about. AND keeps those bits. OR punches a 1 through a hole. XOR flips whatever is under a hole.
Building a mask with a shift
1u << n is a value with only bit n set.
| Expression | Bits | Decimal |
|---|---|---|
1u << 0 |
00000001 |
1 |
1u << 1 |
00000010 |
2 |
1u << 3 |
00001000 |
8 |
The u makes the 1 unsigned. Bit work on a signed int gets awkward: right-shifting a negative value is implementation-defined, and ~ flips every bit of a promoted int, including bits you did not mean to touch. Prefer uint8_t, uint16_t, or uint32_t from <stdint.h> for registers and flags.
Set, clear, toggle, and test
These four lines are the ones you will type most often. n is the bit number.
Set (force the bit to 1)
1 | |
OR with a 1 turns that bit on and leaves every other bit as it was.
1 2 3 4 | |
Clear (force the bit to 0)
1 | |
~(1u << 3) is a mask of all ones except bit 3. AND with that mask clears bit 3 and keeps the rest.
1 2 3 4 | |
Toggle (flip the bit)
1 | |
XOR with 1 flips that bit. A second toggle puts it back.
Test (read the bit)
1 2 3 | |
The result is zero when the bit is clear, and non-zero when it is set. Compare with an explicit mask when you need "these bits, exactly":
1 2 3 | |
Parentheses matter. & binds less tightly than ==, so write (value & mask) == 0, not value & mask == 0.
Several flags in one integer
A status byte can hold many yes/no facts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
One integer, many settings. Peripheral headers do the same thing with names from the datasheet (USART_CR1_UE, GPIO_MODER_MODE5, and so on).
Reading a group of bits
A field is several neighbouring bits, not just one. Mask them, then shift the group down to bit 0.
Bits 2–4 of value sit under the mask 0x38 (0b00111000). Shifting right by 2 moves that group to the bottom:
1 | |
1 2 3 4 5 6 | |
The lowest four bits are the same idea with a simpler mask: value & 0x0Fu.
On a hardware register
Writing a GPIO or timer register is the same pattern. The address comes from the reference manual. volatile tells the compiler the hardware can change the value behind your back. See Pointers in C.
1 2 3 4 | |
Read-modify-write (|=, &=) updates one bit in a copy of the register and writes the whole word back. On some peripherals a write of 1 to a bit already means "clear this flag" or "set only". Check the register description before you invent a mask. Vendor SET_BIT / CLEAR_BIT macros exist so the whole team uses one spelling.
Relevant topics
- Data representation
- C types and macros
- Pointers in C
- Language & toolchain
- Bitwise operators (cppreference)
Starting points
- Write
uint8_t value = 0x0Aand set, clear, toggle, and test bit 3. Print the value in hex after each step and check it by hand. - Pack three flags into one
uint8_twith#definemasks, then turn one flag off without touching the others. - Find
SET_BITor|= (1U <<in your MCU header or a lab project and name the register it changes. - Break precedence on purpose: compare
if (value & mask == 0)withif ((value & mask) == 0)and see which one the compiler warns about.
Focus points
- Use unsigned types (
uint32_t,1u << n) for masks and shifts. - Parenthesize masks inside
if:(value & mask). - Do not shift by the width of the type or more.
1u << 32on a 32-bitunsignedis not a portable "bit 32". - Read the register chapter before a read-modify-write. Some bits are "write 1 to clear".
&is not&&. A bitwise test and a logical test answer different questions.
Key points
- A mask selects bits.
1u << nselects bitn. - Set with
|=, clear with&= ~, toggle with^=, test with&. - Unsigned fixed-width types keep bit patterns predictable across laptop and MCU.
- Peripheral control in C is these four operations with names taken from the datasheet.