CJCCIE Journals

Embedded C Cheat Sheet: Bit Operations, Masks and Common Pitfalls

Cheat SheetsEmbedded C CCIE journals · November 27, 2026

Bit manipulation is the daily language of embedded C. This page covers the patterns and the traps.

Operators

OperatorNameExample (8-bit)
&AND1100 & 1010 = 1000
|OR1100 | 1010 = 1110
^XOR1100 ^ 1010 = 0110
~NOT~00001111 = 11110000
<<Shift left0001 << 2 = 0100
>>Shift right1000 >> 3 = 0001

The four everyday patterns

Four lines you will write for everSet bit nreg |= (1u << n);Clear bit nreg &= ~(1u << n);Toggle bit nreg ^= (1u << n);Test bit nif (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 shiftbit 7MODE bits 6:4mask 0x70, shift 4bit 3bit 2bit 1bit 0Read: (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

HexBinaryHexBinaryHexBinaryHexBinary
000004010081000C1100
100015010191001D1101
2001060110A1010E1110
3001170111B1011F1111

Fixed-width types

TypeBitsRange
uint8_t80 to 255
uint16_t160 to 65,535
uint32_t320 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

KeywordWhy
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.

CJ

Written by CCIE journals

Network security engineer sharing hands-on notes from the journey to CCIE.

0 Comments

Post a Comment

Ready to level up your networking career?

Meet Your Instructor →

Welcome to my blog, dedicated to network and security engineering enthusiasts. Here, you can learn about various vendors and gain valuable insights and resources to excel in the field of network engineering!