Bit manipulation
- C course
- Expert
- Lesson 40/47
- 5 min
Learn bit manipulation patterns in embedded.
Bit manipulation
In embedded systems it is common to change specific bits of a register. A register is 32 bits; each bit controls a hardware feature. Bit manipulation sets, clears and toggles individual bits.
Three core operations: set (reg |= (1 << n)), clear (reg &= ~(1 << n)) and toggle (reg ^= (1 << n)). Here (1 << n) produces a mask: only the n-th bit is 1. |= sets a bit, &= ~ clears it, ^= toggles it. These operations are not atomic; interrupt safety requires care.
Masking and reading
To read a specific bit you AND with a mask: if (reg & (1 << n)). This gives true if the n-th bit is 1, false if 0. To read the lower part of a register: value = reg & 0xFF; (lower 8 bits).
To write multiple bits, first clear then set: reg &= ~0xF; reg |= (value & 0xF);. This replaces the lower 4 bits with the lower 4 bits of value. Masking is the standard way to manage sub-fields of hardware registers in embedded C. Every hardware driver uses these patterns.
Practice Write a bit-set program
Define unsigned int reg = 0;. Set bit 0 with reg |= (1 << 0);. Set bit 2 with reg |= (1 << 2);. In int main(void) print with printf("Kayıt: %d\n", reg) (result should be 5: binary 101).
Starter code
#include <stdio.h>
// reg tanımla ve sıfırla
// bit 0 ve bit 2'yi kur
// main'de değeri yazdırSample solution
#include <stdio.h>
int main(void) {
unsigned int reg = 0;
reg |= (1 << 0);
reg |= (1 << 2);
printf("Kayıt: %d\n", reg);
return 0;
}Expected output
Kayıt: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which operation sets a bit?
- reg &= ~(1 << n)
- reg = (1 << n)
- reg |= (1 << n) Correct answer
- reg ^= (1 << n)
Explanation: |= combines the mask with OR; the bit is set.
2 Complete the set-bit operation
reg |= (1 << ____); /* bit 0'ı kur */
reg |= (1 << 0); /* bit 0'ı kur */
Explanation: (1 << 0) is the mask setting bit 0.
3 Match bit operation
| Term | Meaning |
|---|---|
Set |
|= (1 << n) |
Clear |
&= ~(1 << n) |
Toggle |
^= (1 << n) |
Read |
& (1 << n) |