Theory- Bitwise Operators in Embedded C: AND, OR, XOR, NOT and Shifts Explained Bit by Bit-Free Embedded C Tutorial

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

MODULE 5 · LESSON 5.2 · THEORY

Bitwise Operators in Embedded C: AND, OR, XOR, NOT and Shifts Explained Bit by Bit

Truth tables, bit-level diagrams and compiled examples for & | ^ ~ <>, shifts as multiply and divide, arithmetic versus logical right shift, undefined shift cases, MSB/LSB numbering and precedence traps. Keep this in mind whenever you apply bitwise operators in embedded C.

60 min
Read Time
Beginner → Intermediate
Level
M5 · L2
Module / Lesson

What You Will Learn

✓ Why hardware registers force you to think in bits
✓ The six bitwise operators: & | ^ ~ << >> and their truth tables
✓ Bit-by-bit diagrams of AND, OR, XOR and NOT on real byte values
✓ Left and right shifts as multiplication and division by powers of two
✓ Arithmetic versus logical right shift and the undefined shift cases
✓ Integer promotion surprises with ~ and shifts on small types
✓ MSB, LSB and bit numbering
✓ Bitwise versus logical operators, precedence traps and best practices

Key Terms

BitwiseANDORXORNOTLeft shiftRight shiftMaskMSBLSBArithmetic shiftLogical shiftTruth tableComplementBit field

1. Why Embedded C Needs Bitwise Operators

A microcontroller peripheral is controlled by registers, and a register is a 32-bit word in which individual bits (or small groups of bits) mean different things. One bit enables a clock, another selects a pin mode, another reports that a transmission finished. To change one of them without disturbing its neighbors you need operators that work on individual bits. That is the job of the bitwise operators in embedded C. Many register bugs with bitwise operators in embedded C start here.

Where the arithmetic operators treat a variable as a single number, the bitwise operators treat it as a row of independent switches. They compare, combine or move the bits position by position. This is the core rule behind bitwise operators in embedded C.

One 32-bit register is 32 independent switches
RCC_AHB1ENR
31
0
30
0
29
0
28
0
27
0
26
0
25
0
24
0
23
0
22
0
21
0
20
0
19
0
18
0
17
0
16
0
15
0
14
0
13
0
12
0
11
0
10
0
9
0
8
0
7
0
6
0
5
0
4
1
GPIOEEN
3
0
2
0
1
0
0
0
Setting only bit 4 turns on the clock of GPIOE; the other 31 bits must stay as they are.
OperatorNameWorks onTypical use
&ANDeach bit pairclear bits, test bits, apply a mask
|OReach bit pairset bits
^XOReach bit pairtoggle bits, find differences
~NOT (complement)each bitinvert, build clear-masks
<<left shiftwhole valuebuild a mask, multiply by 2n
>>right shiftwhole valueextract a field, divide by 2n

2. Bitwise AND (&)

AND produces a 1 in a result bit only if both input bits are 1. Its two classic jobs are clearing bits (AND with 0 forces a bit to 0) and testing bits (AND with a mask keeps only the bits you care about). Reviewers check bitwise operators in embedded C first in driver code.

ABA & B
000
010
100
111
0xCA & 0x0F keeps the lower nibble and clears the upper nibble
A = 202
7
1
6
1
5
0
4
0
3
1
2
0
1
1
0
0
B = 15  (AND)
0
0
0
0
1
1
1
1
Result = 10
0
0
0
0
1
0
1
0
Where B has 0 the result is forced to 0; where B has 1 the result copies A.
and_demo.c
#include <stdio.h> #include <stdint.h> static void print_bits(const char *label, uint8_t v) { printf(“%-12s “, label); for (int i = 7; i >= 0; i–) printf(“%d”, (v >> i) & 1); printf(” (0x%02X = %3u)\n”, v, v); } int main(void) { uint8_t a = 0xCA, mask = 0x0F; print_bits(“a”, a); print_bits(“mask”, mask); print_bits(“a & mask”, a & mask); uint8_t status = 0x24; /* 0010 0100 */ printf(“bit 2 of status set? %s\n”, (status & (1u << 2)) ? “yes” : “no”); printf(“bit 3 of status set? %s\n”, (status & (1u << 3)) ? “yes” : “no”); printf(“is 44 odd? %u is 45 odd? %u\n”, 44u & 1u, 45u & 1u); return 0; }
Output (verified by compiling and running)
a 11001010 (0xCA = 202) mask 00001111 (0x0F = 15) a & mask 00001010 (0x0A = 10) bit 2 of status set? yes bit 3 of status set? no is 44 odd? 0 is 45 odd? 1
  • Mask: x & 0x0F keeps only the low 4 bits.
  • Test: if (flags & FLAG_READY) is non-zero when that bit is set.
  • Clear: x &= ~(1u << n) sets bit n to 0 and leaves the rest (Lesson 5.3).
  • Odd/even: n & 1 is the lowest bit.
  • Modulo by a power of two: x & (N - 1) equals x % N for unsigned x when N is 2, 4, 8, 16 …

3. Bitwise OR (|)

OR produces a 1 if at least one input bit is 1. OR with 1 forces a bit to 1, and OR with 0 leaves it unchanged, which makes OR the natural way to set bits. Interviewers test bitwise operators in embedded C on exactly this point.

ABA | B
000
011
101
111
0x30 | 0x05 combines two sets of bits
A = 48
7
0
6
0
5
1
4
1
3
0
2
0
1
0
0
0
B = 5  (OR)
0
0
0
0
0
1
0
1
Result = 53
0
0
1
1
0
1
0
1
or_demo.c
#include <stdio.h> #include <stdint.h> static void print_bits(const char *label, uint8_t v) { printf(“%-12s “, label); for (int i = 7; i >= 0; i–) printf(“%d”, (v >> i) & 1); printf(” (0x%02X = %3u)\n”, v, v); } int main(void) { uint8_t reg = 0x30; print_bits(“reg”, reg); reg |= 0x05; /* set bits 0 and 2 */ print_bits(“reg |= 0x05”, reg); reg |= 0x05; /* doing it again changes nothing */ print_bits(“again”, reg); return 0; }
Output (verified by compiling and running)
reg 00110000 (0x30 = 48) reg |= 0x05 00110101 (0x35 = 53) again 00110101 (0x35 = 53)
Idempotent: Setting a bit that is already set does nothing. That is why reg |= mask; is safe to repeat, for example in an init function that may run twice.

4. Bitwise XOR (^)

XOR (exclusive OR) produces a 1 when the two input bits are different. XOR with 1 flips a bit; XOR with 0 leaves it alone. That makes it the operator for toggling bits and for finding which bits differ between two values.

ABA ^ B
000
011
101
110
0xF0 ^ 0x3C: bits that differ become 1
A = 240
7
1
6
1
5
1
4
1
3
0
2
0
1
0
0
0
B = 60  (XOR)
0
0
1
1
1
1
0
0
Result = 204
1
1
0
0
1
1
0
0
xor_demo.c
#include <stdio.h> #include <stdint.h> static void print_bits(const char *label, uint8_t v) { printf(“%-12s “, label); for (int i = 7; i >= 0; i–) printf(“%d”, (v >> i) & 1); printf(” (0x%02X = %3u)\n”, v, v); } int main(void) { uint8_t led = 0x00; for (int i = 0; i < 4; i++) { led ^= 0x01; /* toggle bit 0 */ printf(“toggle %d -> bit0 = %u\n”, i + 1, led & 1); } uint8_t before = 0xB5, after = 0xB1; print_bits(“before”, before); print_bits(“after”, after); print_bits(“changed”, before ^ after); /* 1 where they differ */ uint8_t x = 0x5A; print_bits(“x”, x); print_bits(“x ^ x”, x ^ x); /* a value XOR itself is 0 */ print_bits(“x ^ 0”, x ^ 0); /* XOR with 0 is the value */ return 0; }
Output (verified by compiling and running)
toggle 1 -> bit0 = 1 toggle 2 -> bit0 = 0 toggle 3 -> bit0 = 1 toggle 4 -> bit0 = 0 before 10110101 (0xB5 = 181) after 10110001 (0xB1 = 177) changed 00000100 (0x04 = 4) x 01011010 (0x5A = 90) x ^ x 00000000 (0x00 = 0) x ^ 0 01011010 (0x5A = 90)

Useful XOR properties

PropertyExpressionUse
Self-cancellingx ^ x == 0Compare two values: zero means equal
Identityx ^ 0 == xLeave bits unchanged
Double toggle(x ^ m) ^ m == xSimple reversible encoding, checksums
Commutative and associativea ^ b ^ a == bSwap without a temporary (a curiosity)
The XOR swap is a trick, not a recommendation: a ^= b; b ^= a; a ^= b; swaps two variables without a temporary, but it fails when both names refer to the same object (the value becomes 0) and compilers do a normal swap with registers at least as fast. Use a temporary variable.

5. Bitwise NOT (~) and the Promotion Trap

The complement operator ~ is unary and flips every bit: 0 becomes 1 and 1 becomes 0. Combined with AND it builds the “everything except this bit” mask used to clear bits: reg &= ~(1u << n);.

A~A
01
10
~0x0F on an 8-bit value
x = 0x0F
7
0
6
0
5
0
4
0
3
1
2
1
1
1
0
1
~x = 0xF0
1
1
1
1
0
0
0
0

There is a subtle trap with small types. Operands narrower than int are promoted to int before the operator is applied (Lesson 3.3). The complement of a promoted byte therefore has 32 bits:

not_promotion.c
#include <stdio.h> #include <stdint.h> int main(void) { uint8_t x = 0x0F; printf(“~x = 0x%08X\n”, (unsigned)~x); /* promoted to int first */ printf(“(uint8_t)~x = 0x%02X\n”, (unsigned)(uint8_t)~x); /* cast back to 8 bits */ uint8_t y = ~x; /* stored: upper bits dropped */ printf(“uint8_t y = ~x -> 0x%02X\n”, y); if (~x == 0xF0) printf(“~x == 0xF0 : true\n”); else printf(“~x == 0xF0 : FALSE (compares 0xFFFFFFF0 with 0xF0)\n”); if ((uint8_t)~x == 0xF0) printf(“(uint8_t)~x == 0xF0 : true\n”); return 0; }
Output (verified by compiling and running)
~x = 0xFFFFFFF0 (uint8_t)~x = 0xF0 uint8_t y = ~x -> 0xF0 ~x == 0xF0 : FALSE (compares 0xFFFFFFF0 with 0xF0) (uint8_t)~x == 0xF0 : true
Rule: When you compare the complement of a uint8_t or uint16_t with a constant, cast the result back: (uint8_t)~x. This is also why MISRA C restricts ~ and shifts on small unsigned types.

6. Shift Operators: << and >>

Shifts slide the whole bit pattern left or right by a number of positions. x << n moves every bit n places toward the MSB and fills the vacated low bits with 0. x >> n moves bits toward the LSB; the bits that fall off the end are lost.

0x13 << 2 and 0x13 >> 2 (19 becomes 76 and 4)
x = 19
7
0
6
0
5
0
4
1
3
0
2
0
1
1
0
1
x << 2 = 76
0
1
0
0
1
1
0
zero
0
zero
x >> 2 = 4
0
zero
0
zero
0
0
0
1
0
0
In the right shift the two lowest bits (1, 1) are discarded.
shift_demo.c
#include <stdio.h> #include <stdint.h> static void print_bits(const char *label, uint8_t v) { printf(“%-12s “, label); for (int i = 7; i >= 0; i–) printf(“%d”, (v >> i) & 1); printf(” (0x%02X = %3u)\n”, v, v); } int main(void) { uint8_t x = 19; print_bits(“x”, x); print_bits(“x << 1”, (uint8_t)(x << 1)); print_bits(“x << 2”, (uint8_t)(x << 2)); print_bits(“x >> 1”, x >> 1); print_bits(“x >> 2”, x >> 2); printf(“\n1 << n gives a single-bit mask:\n”); for (int n = 0; n < 8; n += 3) printf(” 1 << %d = 0x%02X = %u\n”, n, 1u << n, 1u << n); uint16_t v = 0xAB12; uint16_t pushed = (uint16_t)(v << 8); /* 0xAB is pushed out of the top */ printf(“\n0xAB12 << 8 stored in 16 bits = 0x%04X (high byte lost)\n”, pushed); printf(“… then >> 8 = 0x%02X (the lost byte does not come back)\n”, pushed >> 8); return 0; }
Output (verified by compiling and running)
x 00010011 (0x13 = 19) x << 1 00100110 (0x26 = 38) x << 2 01001100 (0x4C = 76) x >> 1 00001001 (0x09 = 9) x >> 2 00000100 (0x04 = 4) 1 << n gives a single-bit mask: 1 << 0 = 0x01 = 1 1 << 3 = 0x08 = 8 1 << 6 = 0x40 = 64 0xAB12 << 8 stored in 16 bits = 0x1200 (high byte lost) … then >> 8 = 0x12 (the lost byte does not come back)

Shift as fast multiplication and division

Shifting left by n multiplies an unsigned value by 2n (as long as no 1-bit is pushed out of the top); shifting right by n divides by 2n, discarding the remainder.

ExpressionSame asExample (x = 12)
x << 1x * 224
x << 3x * 896
x >> 1x / 26
x >> 2x / 43
x >> 3x / 8 (truncated)1
Do not hand-optimise: Modern compilers turn x * 8 and x / 8 into shifts automatically. Write the shift when you mean “move bits” (building masks, extracting fields), and write * or / when you mean arithmetic.

7. Arithmetic vs Logical Right Shift and Undefined Shifts

When the operand of >> is unsigned, the vacated high bits are filled with 0 (a logical shift). When the operand is a negative signed value, the C standard says the result is implementation-defined. GCC for ARM, like almost every compiler, performs an arithmetic shift: the sign bit is copied into the vacated positions so that the value stays negative.

shift_signed.c
#include <stdio.h> #include <stdint.h> int main(void) { int8_t s = –16; /* 1111 0000 */ uint8_t u = 0xF0; /* same bits, unsigned */ printf(“signed -16 >> 2 = %d\n”, s >> 2); printf(“unsigned 240 >> 2 = %u\n”, u >> 2); int32_t neg = –64; printf(“-64 >> 3 = %d (arithmetic shift keeps the sign)\n”, neg >> 3); printf(“(uint32_t)-64 >> 3 = %u (logical shift fills with zeros)\n”, (unsigned)((uint32_t)neg >> 3)); return 0; }
Output (verified by compiling and running)
signed -16 >> 2 = -4 unsigned 240 >> 2 = 60 -64 >> 3 = -8 (arithmetic shift keeps the sign) (uint32_t)-64 >> 3 = 536870904 (logical shift fills with zeros)
Same bit pattern 1111 0000, two different right shifts by 2
int8_t -16
7
1
6
1
5
1
4
1
3
0
2
0
1
0
0
0
>> 2 = -4
1
sign
1
copy
1
1
1
1
0
0
uint8_t 240
7
1
6
1
5
1
4
1
3
0
2
0
1
0
0
0
>> 2 = 60
0
zero
0
zero
1
1
1
1
0
0

Shift cases that are undefined behavior

CaseExampleProblem
Count ≥ width of the (promoted) type1u << 32 on a 32-bit unsignedUndefined; ARM hardware uses only the low byte of the count and gives 0 for 32 or more, but the compiler may do anything
Negative shift countx >> -1Undefined
Left shift of a negative signed value-1 << 3Undefined (C11)
Left shift that overflows a signed type1 << 31 as intUndefined; use 1u << 31
Always shift unsigned values: Write 1u << n, not 1 << n, and keep the operand of >> unsigned when you want a logical shift. For a mask wider than 32 bits use 1ULL.

8. MSB, LSB and Bit Numbering

The LSB (least significant bit) is bit 0, the rightmost bit, worth 1. The MSB (most significant bit) is the leftmost, bit 7 of a byte or bit 31 of a word; in a signed type it is the sign bit. Reference manuals number bits from 0 on the right, exactly as C shifts do, so 1u << n is the mask for bit n.

Bit numbering of a 32-bit register (STM32 reference manual style)
32-bit word
31
1
MSB
30
0
29
0
28
0
27
0
26
0
25
0
24
0
23
0
22
0
21
0
20
0
19
0
18
0
17
0
16
0
15
0
14
0
13
0
12
0
11
0
10
0
9
0
8
0
7
0
6
0
5
0
4
0
3
0
2
0
1
0
0
1
LSB
bit 31 = 1u << 31 = 0x80000000  ·  bit 0 = 1u << 0 = 0x00000001

Extracting bytes and fields with shift + mask

extract.c
#include <stdio.h> #include <stdint.h> int main(void) { uint32_t word = 0xA1B2C3D4; printf(“byte 3 (MSB) : 0x%02X\n”, (unsigned)((word >> 24) & 0xFF)); printf(“byte 2 : 0x%02X\n”, (unsigned)((word >> 16) & 0xFF)); printf(“byte 1 : 0x%02X\n”, (unsigned)((word >> 8) & 0xFF)); printf(“byte 0 (LSB) : 0x%02X\n”, (unsigned)( word & 0xFF)); uint32_t rebuilt = ((uint32_t)0xA1 << 24) | ((uint32_t)0xB2 << 16) | ((uint32_t)0xC3 << 8) | 0xD4; printf(“rebuilt : 0x%08X\n”, (unsigned)rebuilt); /* a 3-bit field at bits [6:4] */ uint32_t reg = 0x00000050; /* 0101 0000 -> field = 101b = 5 */ printf(“field[6:4] : %u\n”, (unsigned)((reg >> 4) & 0x7)); return 0; }
Output (verified by compiling and running)
byte 3 (MSB) : 0xA1 byte 2 : 0xB2 byte 1 : 0xC3 byte 0 (LSB) : 0xD4 rebuilt : 0xA1B2C3D4 field[6:4] : 5

The pattern (value >> position) & mask reads a field; the reverse, (field & mask) << position, writes one. Lesson 5.3 turns these into the five standard register idioms.

9. Bitwise vs Logical Operators

BitwiseLogical
Symbols& | ^ ~&& || !
Operates oneach bit position separatelythe whole value as true/false
Resulta number of the same widthexactly 0 or 1
Short-circuits?No: both operands always evaluatedYes
Example: 6 and 36 & 3 == 26 && 3 == 1
bitwise_vs_logical.c
#include <stdio.h> int main(void) { int a = 6, b = 3; /* 0110 and 0011 */ printf(“a & b = %d\n”, a & b); printf(“a && b = %d\n”, a && b); printf(“a | b = %d\n”, a | b); printf(“a || b = %d\n”, a || b); printf(“~a = %d\n”, ~a); printf(“!a = %d\n”, !a); int flags = 0x04, READY = 0x02; printf(“flags & READY -> %d (bit not set)\n”, flags & READY); printf(“flags && READY -> %d (both non-zero: WRONG test)\n”, flags && READY); return 0; }
Output (verified by compiling and running)
a & b = 2 a && b = 1 a | b = 7 a || b = 1 ~a = -7 !a = 0 flags & READY -> 0 (bit not set) flags && READY -> 1 (both non-zero: WRONG test)

Precedence traps with bitwise operators

  • Comparison binds tighter than &, ^ and |. x & 4 == 4 means x & (4 == 4). Write (x & 4) == 4.
  • Shifts bind tighter than comparison, and + - bind tighter than shifts: 1 << n + 1 is 1 << (n + 1).
  • Bitwise precedence order: &, then ^, then |. Parenthesise when mixing them.
Rule of thumb: Always put parentheses around every bitwise sub-expression. MISRA C and most embedded coding standards require it, and it removes this whole class of bugs.

10. Common Mistakes With Bitwise Operators

Mistake 1 — using && where & was meant (or the reverse): The logical operator tests the whole value; it cannot test a single bit.
Mistake 2 — forgetting parentheses with ==: if (reg & MASK == MASK) tests the wrong thing.
Mistake 3 — signed shifts: 1 << 31 overflows int. Use 1u.
Mistake 4 — ~ on small unsigned types: ~x for a uint8_t is a 32-bit int; compare with a cast.
Mistake 5 — shift count too large: 1u << 32 is undefined; check the count when it comes from data.
Mistake 6 — assuming >> always divides signed numbers: -7 >> 1 is -4 on GCC (rounds toward minus infinity) while -7 / 2 is -3.
Mistake 7 — plain 1 as a mask for bit 31 or above: 1 << 40 is undefined; use 1ULL.
Mistake 8 — using = where |= was meant on a register: Plain assignment overwrites all other bits of the register.

11. Best Practices for Bitwise Operators in Embedded C

  • Use unsigned types (uint8_t, uint16_t, uint32_t) for anything you shift or mask.
  • Write masks as (1u << n) or named constants (#define LED_PIN (1u << 12)) and never as bare numbers.
  • Parenthesise every bitwise sub-expression.
  • Use hexadecimal for masks and registers so the bits are visible: 0x0000F000.
  • Cast back to the narrow type after ~ or a left shift on uint8_t/uint16_t.
  • Prefer * and / for arithmetic; use shifts only for bit work.
  • Test with the boundary bits (0, 7, 15, 31) when you write a new mask expression.
  • Name your fields: use CMSIS macros such as GPIO_ODR_OD12 instead of magic numbers.

Key Takeaways — Lesson 5.2

  • Bitwise operators in embedded C act position by position: & (both), | (either), ^ (different), ~ (invert).
  • AND clears or tests bits, OR sets bits, XOR toggles bits, NOT builds clear-masks.
  • x << n multiplies an unsigned value by 2n; x >> n divides by 2n.
  • Right shift of a negative signed value is implementation-defined (arithmetic on GCC); shifting by the type width or more is undefined.
  • ~ and shifts promote small types to int; cast the result back.
  • Bit 0 is the LSB; 1u << n is the mask for bit n.
  • Bitwise and logical operators are not interchangeable, and comparison binds tighter than &, ^, |.

Frequently Asked Questions

What is the difference between & and && in C?
& is bitwise AND: it combines two values bit by bit and gives a number. && is logical AND: it treats each operand as true or false, short-circuits, and gives 0 or 1. For 6 and 3, 6 & 3 is 2 but 6 && 3 is 1.
How do I check whether a bit is set?
AND with a mask and test for non-zero: if (reg & (1u << n)). For a multi-bit mask compare the result with the mask: (reg & MASK) == MASK.
What does the XOR operator do?
It sets a result bit to 1 only when the two input bits differ. XOR with 1 toggles a bit, XOR with 0 keeps it, and x ^ x is always 0.
What is the difference between arithmetic and logical right shift?
A logical right shift fills the vacated high bits with 0 (used for unsigned values). An arithmetic right shift copies the sign bit into them (used by GCC for negative signed values), preserving the sign.
Why is 1 << 31 a problem?
The constant 1 is a signed int; shifting a 1 into the sign bit overflows a signed type, which is undefined behavior. Write 1u << 31.
Is x << 1 faster than x * 2?
On a modern compiler they produce the same machine code, so write whichever expresses your intent. Use the shift when you are manipulating bits, the multiplication when you are doing arithmetic.

Ready to practise?

Next: truth tables with worked examples, shift visualisations, byte-level demos and programs using bit operations.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *