Bit manipulation is the daily language of embedded C. This page covers the patterns and the traps.
🖨 Print or save as PDF
Operators Operator Name Example (8-bit) &AND 1100 & 1010 = 1000 |OR 1100 | 1010 = 1110 ^XOR 1100 ^ 1010 = 0110 ~NOT ~00001111 = 11110000 <<Shift left 0001 << 2 = 0100 >>Shift right 1000 >> 3 = 0001
The four everyday patterns Four lines you will write for ever Set bit n reg |= (1u << n); Clear bit n reg &= ~(1u << n); Toggle bit n reg ^= (1u << n); Test bit n if (reg & (1u << n)) The four patterns side by side reg |= (1u << n); /* set bit n */
reg &= ~(1u << n); /* clear bit n */
reg ^= (1u << n); /* toggle bit n */
if ((reg >> n) & 1u) /* test bit n */ Fields wider than one bit A field is a mask and a shift bit 7 MODE bits 6:4 mask 0x70, shift 4 bit 3 bit 2 bit 1 bit 0 Read: (reg & 0x70) >> 4 Write: reg = (reg & ~0x70) | ((value << 4) & 0x70) Mask first, then shift #define MASK(width) ((1u << (width)) - 1u)
value = (reg >> pos) & MASK(width); /* read */
reg = (reg & ~(MASK(width) << pos))
| ((value & MASK(width)) << pos); /* write */ Hex and binary Hex Binary Hex Binary Hex Binary Hex Binary 0 0000 4 0100 8 1000 C 1100 1 0001 5 0101 9 1001 D 1101 2 0010 6 0110 A 1010 E 1110 3 0011 7 0111 B 1011 F 1111
Fixed-width types Type Bits Range uint8_t8 0 to 255 uint16_t16 0 to 65,535 uint32_t32 0 to 4,294,967,295 int8_t8 -128 to 127
Include <stdint.h>. Use these instead of int when the size matters, which in embedded code is almost always.
Keywords that matter Keyword Why volatileThe value can change outside the program (a hardware register, an interrupt). Stops the compiler optimising reads away. constRead-only. Often placed in flash instead of RAM. staticKeeps its value between calls, or limits a name to one file.
Pitfalls Precedence: == binds tighter than &. Write (reg & MASK) == 0, never reg & MASK == 0.Shift too far: shifting by the width of the type or more is undefined behaviour.Signed shifts: right-shifting a negative number depends on the compiler. Use unsigned types for bit work.Plain 1: 1 << 31 overflows a signed int. Write 1u << 31.Byte order: little-endian stores the lowest byte first, big-endian the highest. Network byte order is big-endian.Read-modify-write: an interrupt can change a register between your read and your write. Protect shared registers.CCIE Journals cheat sheet. Free to print and share for study.
0 Comments
Post a Comment