MODULE 5 · LESSON 5.2 · EXAMPLES
Bitwise Operators Examples: Truth Tables, Shifts, Popcount, RGB565 and XOR Checksums
Ten worked examples with real output: truth tables, byte-level AND/OR/XOR diagrams, LED chaser, set-bit counting, power-of-two idioms, bit reversal, RGB565 packing, parity, signed shifts and endianness. Study this one of the bitwise operators examples before the next.
Beginner → Intermediate
Level
Real output
Compiled and run
Bitwise Operators Examples: What This Page Covers
These bitwise operators examples start with the truth tables generated by a program, move to worked byte-level problems, and finish with six small algorithms that firmware really uses. Every program was compiled and executed. These bitwise operators examples build on each other.
| # | Example | Skill |
|---|
| 1 | Truth tables printed by a program | AND, OR, XOR, NOT |
| 2 | Worked byte examples: 0xB6 and 0x3C | Bit-by-bit evaluation |
| 3 | Walking a 1 across a byte (LED chaser) | Shifts |
| 4 | Counting set bits | x & (x-1) |
| 5 | Power-of-two test and mask instead of modulo | Masks |
| 6 | Swapping nibbles and reversing bits | Shift + mask |
| 7 | Packing and unpacking RGB565 | Bit fields |
| 8 | XOR parity and a simple checksum | XOR |
| 9 | Signed shifts versus division | Arithmetic shift |
| 10 | Bytes of a word: shifts versus memory order | Endianness |
| 11 | Mini exercises | Self-test |
Example 1: Truth Tables Printed by a Program
Problem: Let the compiler produce the truth tables of the four basic bitwise operations, so you can check them against the theory. Of all the bitwise operators examples this is the most used in drivers.
truth.c
#include <stdio.h>
int main(void)
{
printf(” A B | A&B A|B A^B\n”);
printf(“—–+————-\n”);
for (int a = 0; a <= 1; a++)
for (int b = 0; b <= 1; b++)
printf(” %d %d | %d %d %d\n”, a, b, a & b, a | b, a ^ b);
printf(“\n A | ~A (1-bit)\n”);
for (int a = 0; a <= 1; a++)
printf(” %d | %d\n”, a, ~a & 1);
return 0;
}
Output (verified by compiling and running)
A B | A&B A|B A^B
—–+————-
0 0 | 0 0 0
0 1 | 0 1 1
1 0 | 0 1 1
1 1 | 1 1 0
A | ~A (1-bit)
0 | 1
1 | 0
| Operator | Rule in words | Mnemonic |
|---|
& | 1 only if both bits are 1 | both |
| | 1 if at least one bit is 1 | either |
^ | 1 if the bits differ | different |
~ | flip the bit | invert |
Why ~a & 1: A bare ~a on an int inverts all 32 bits and gives -1 or -2. Masking with 1 keeps only the bit of interest.
Example 2: Worked Byte Examples With 0xB6 and 0x3C
Problem: Evaluate the four operations on a = 0xB6 (1011 0110) and b = 0x3C (0011 1100) by hand, then confirm with the program. Keep these bitwise operators examples handy when reading a reference manual.
byte_ops.c
#include <stdio.h>
#include <stdint.h>
static void bits8(const char *label, uint8_t v)
{
printf(“%-10s “, label);
for (int i = 7; i >= 0; i–) printf(“%d%s”, (v >> i) & 1, i == 4 ? ” “ : “”);
printf(” 0x%02X\n”, v);
}
int main(void)
{
uint8_t a = 0xB6, b = 0x3C;
bits8(“a”, a);
bits8(“b”, b);
bits8(“a & b”, a & b);
bits8(“a | b”, a | b);
bits8(“a ^ b”, a ^ b);
bits8(“~a”, (uint8_t)~a);
return 0;
}
Output (verified by compiling and running)
a 1011 0110 0xB6
b 0011 1100 0x3C
a & b 0011 0100 0x34
a | b 1011 1110 0xBE
a ^ b 1000 1010 0x8A
~a 0100 1001 0x49
a & b = 0x34: both bits must be 1
a | b = 0xBE: either bit is enough
a ^ b = 0x8A: only the differing positions
Example 3: Walking a 1 Across a Byte (LED Chaser)
Problem: Light eight LEDs one after another. Each step shifts a single 1 one position. On the STM32F407 Discovery you would write the value to an output data register, for example to the lower bits of GPIOD->ODR.
chaser.c
#include <stdio.h>
#include <stdint.h>
int main(void)
{
printf(“walking 1 (shift left):\n”);
for (int i = 0; i < 8; i++) {
uint8_t led = (uint8_t)(1u << i);
printf(” i=%d “, i);
for (int b = 7; b >= 0; b–) printf(“%c”, (led >> b) & 1 ? ‘#’ : ‘.’);
printf(” 0x%02X\n”, led);
}
printf(“\nKnight Rider bounce (shift both ways):\n”);
uint8_t led = 0x01; int dir = 1;
for (int step = 0; step < 14; step++) {
printf(” “);
for (int b = 7; b >= 0; b–) printf(“%c”, (led >> b) & 1 ? ‘#’ : ‘.’);
printf(“\n”);
if (dir) { led <<= 1; if (led == 0x80) dir = 0; }
else { led >>= 1; if (led == 0x01) dir = 1; }
}
return 0;
}
Output (verified by compiling and running)
walking 1 (shift left):
i=0 …….# 0x01
i=1 ……#. 0x02
i=2 …..#.. 0x04
i=3 ….#… 0x08
i=4 …#…. 0x10
i=5 ..#….. 0x20
i=6 .#…… 0x40
i=7 #……. 0x80
Knight Rider bounce (shift both ways):
…….#
……#.
…..#..
….#…
…#….
..#…..
.#……
#…….
.#……
..#…..
…#….
….#…
…..#..
……#.
1u << i builds the mask for LED i in one expression.led <<= 1 moves the lit LED toward the MSB; led >>= 1 moves it back.- The bounce stops at the end positions by comparing with
0x80 and 0x01.
Example 4: Counting Set Bits
Problem: Count how many bits of a word are 1 (used for parity, bitmap occupancy and error counting). Compare the obvious loop with Brian Kernighan’s trick.
popcount.c
#include <stdio.h>
#include <stdint.h>
static unsigned popcount_loop(uint32_t x)
{
unsigned c = 0;
while (x) { c += x & 1u; x >>= 1; } /* test the lowest bit, shift down */
return c;
}
static unsigned popcount_kernighan(uint32_t x)
{
unsigned c = 0;
while (x) { x &= x – 1; c++; } /* each step clears the lowest 1 bit */
return c;
}
int main(void)
{
uint32_t tests[] = { 0x00, 0x01, 0x0F, 0xA5, 0xFF, 0x80000001u, 0xFFFFFFFFu };
printf(” value loop kernighan\n”);
for (unsigned i = 0; i < sizeof tests / sizeof tests[0]; i++)
printf(“0x%08X %4u %9u\n”, (unsigned)tests[i], popcount_loop(tests[i]), popcount_kernighan(tests[i]));
uint32_t x = 0xB4; /* 1011 0100 */
printf(“\nx = 0xB4:\n”);
for (int i = 0; i < 4 && x; i++) {
printf(” x = 0x%02X, x-1 = 0x%02X, x&(x-1) = 0x%02X\n”, (unsigned)x, (unsigned)(x – 1), (unsigned)(x & (x – 1)));
x &= x – 1;
}
return 0;
}
Output (verified by compiling and running)
value loop kernighan
0x00000000 0 0
0x00000001 1 1
0x0000000F 4 4
0x000000A5 4 4
0x000000FF 8 8
0x80000001 2 2
0xFFFFFFFF 32 32
x = 0xB4:
x = 0xB4, x-1 = 0xB3, x&(x-1) = 0xB0
x = 0xB0, x-1 = 0xAF, x&(x-1) = 0xA0
x = 0xA0, x-1 = 0x9F, x&(x-1) = 0x80
x = 0x80, x-1 = 0x7F, x&(x-1) = 0x00
Why x & (x – 1) removes the lowest 1
Subtracting 1 flips the lowest 1 and every 0 below it; AND keeps only what both share.
The Kernighan loop runs once per set bit rather than once per bit position. On Cortex-M4 you can also use the compiler built-in __builtin_popcount(), which calls a small library routine because the core has no popcount instruction.
Example 5: Power-of-Two Test, Masks Instead of Modulo, Aligning an Address
Problem: Three firmware idioms, all based on the fact that a power of two N has a single 1 bit, so N - 1 is a row of ones below it.
pow2.c
#include <stdio.h>
#include <stdint.h>
static int is_pow2(uint32_t x) { return x != 0 && (x & (x – 1)) == 0; }
int main(void)
{
uint32_t v[] = { 0, 1, 2, 3, 6, 8, 64, 100, 1024, 4096 };
for (unsigned i = 0; i < sizeof v / sizeof v[0]; i++)
printf(“%5u -> %s\n”, (unsigned)v[i], is_pow2(v[i]) ? “power of two” : “no”);
printf(“\nmask instead of modulo (N = 16):\n”);
for (uint32_t x = 14; x < 20; x++)
printf(” %2u %% 16 = %2u %2u & 15 = %2u\n”, (unsigned)x, (unsigned)(x % 16), (unsigned)x, (unsigned)(x & 15));
printf(“\nalign up to a multiple of 8:\n”);
uint32_t addr[] = { 0x20000001, 0x20000008, 0x2000000D };
for (int i = 0; i < 3; i++)
printf(” 0x%08X -> 0x%08X\n”, (unsigned)addr[i], (unsigned)((addr[i] + 7u) & ~7u));
return 0;
}
Output (verified by compiling and running)
0 -> no
1 -> power of two
2 -> power of two
3 -> no
6 -> no
8 -> power of two
64 -> power of two
100 -> no
1024 -> power of two
4096 -> power of two
mask instead of modulo (N = 16):
14 % 16 = 14 14 & 15 = 14
15 % 16 = 15 15 & 15 = 15
16 % 16 = 0 16 & 15 = 0
17 % 16 = 1 17 & 15 = 1
18 % 16 = 2 18 & 15 = 2
19 % 16 = 3 19 & 15 = 3
align up to a multiple of 8:
0x20000001 -> 0x20000008
0x20000008 -> 0x20000008
0x2000000D -> 0x20000010
| Idiom | Expression | Why it works |
|---|
| Power of two? | x != 0 && (x & (x-1)) == 0 | A single 1 bit is cleared by x & (x-1) |
| Fast modulo | x & (N-1) | Keeps the low log2(N) bits |
| Align up | (x + N-1) & ~(N-1) | Add up to N-1, then clear the low bits |
Only for unsigned values and powers of two: For a negative signed number x & (N-1) does not equal x % N, and for N that is not a power of two the mask idiom is simply wrong.
Example 6: Swapping Nibbles, Reversing Bits and Rotating
Problem: Move bits around inside a byte. Reversal is needed when a peripheral transmits the least significant bit first but a protocol expects the opposite; nibble swapping appears in BCD handling.
bit_moves.c
#include <stdio.h>
#include <stdint.h>
static void bits8(const char *label, uint8_t v)
{
printf(“%-10s “, label);
for (int i = 7; i >= 0; i–) printf(“%d%s”, (v >> i) & 1, i == 4 ? ” “ : “”);
printf(” 0x%02X\n”, v);
}
static uint8_t swap_nibbles(uint8_t v) { return (uint8_t)((v << 4) | (v >> 4)); }
static uint8_t reverse_bits(uint8_t v)
{
uint8_t r = 0;
for (int i = 0; i < 8; i++) {
r = (uint8_t)((r << 1) | (v & 1u)); /* take the lowest bit of v, append to r */
v >>= 1;
}
return r;
}
int main(void)
{
uint8_t x = 0x3A;
bits8(“x”, x);
bits8(“swap”, swap_nibbles(x));
bits8(“reverse”, reverse_bits(x));
bits8(“rev(rev)”, reverse_bits(reverse_bits(x)));
uint8_t y = 0xC5;
bits8(“y”, y);
bits8(“rot left”, (uint8_t)((y << 1) | (y >> 7)));
return 0;
}
Output (verified by compiling and running)
x 0011 1010 0x3A
swap 1010 0011 0xA3
reverse 0101 1100 0x5C
rev(rev) 0011 1010 0x3A
y 1100 0101 0xC5
rot left 1000 1011 0x8B
Nibble swap: (v << 4) | (v >> 4)
Rotate vs shift: A shift loses the bits that leave the register; a rotate feeds them back in at the other end. C has no rotate operator, but for 32-bit unsigned values GCC recognises (x << n) | (x >> (32 - n)) and emits a single ARM ROR instruction.
Example 7: Packing and Unpacking an RGB565 Color
Problem: Store a color in 16 bits as the TFT display of the STM32F4 Discovery expects: 5 bits red, 6 bits green, 5 bits blue.
rgb565.c
#include <stdio.h>
#include <stdint.h>
/* RGB565: RRRRR GGGGGG BBBBB (16 bits) */
static uint16_t pack565(uint8_t r, uint8_t g, uint8_t b)
{
return (uint16_t)(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3));
}
static void unpack565(uint16_t c, uint8_t *r, uint8_t *g, uint8_t *b)
{
*r = (uint8_t)(((c >> 11) & 0x1F) << 3);
*g = (uint8_t)(((c >> 5) & 0x3F) << 2);
*b = (uint8_t)(( c & 0x1F) << 3);
}
int main(void)
{
uint8_t r = 255, g = 128, b = 64;
uint16_t c = pack565(r, g, b);
printf(“RGB888 (%3u,%3u,%3u) -> RGB565 0x%04X\n”, r, g, b, c);
uint8_t r2, g2, b2;
unpack565(c, &r2, &g2, &b2);
printf(“back to RGB888 (%3u,%3u,%3u) (lowest bits were dropped)\n”, r2, g2, b2);
printf(“red field = %u\n”, (c >> 11) & 0x1F);
printf(“green field = %u\n”, (c >> 5) & 0x3F);
printf(“blue field = %u\n”, c & 0x1F);
return 0;
}
Output (verified by compiling and running)
RGB888 (255,128, 64) -> RGB565 0xFC08
back to RGB888 (248,128, 64) (lowest bits were dropped)
red field = 31
green field = 32
blue field = 8
To pack, shift each channel down to its width and then up to its position, then OR. To unpack, shift down, mask to the field width and shift back up. These two functions are the template for every bit-field in a register: a field of width w at position p is read with (reg >> p) & ((1u << w) - 1).
Example 8: XOR Parity and a Simple Checksum
Problem: Detect a transmission error. XOR of all bytes in a frame (a longitudinal redundancy check) is zero when the checksum byte is included and nothing changed.
xor_checksum.c
#include <stdio.h>
#include <stdint.h>
static uint8_t parity_bit(uint8_t v) /* 1 if the number of 1 bits is odd */
{
v ^= v >> 4;
v ^= v >> 2;
v ^= v >> 1;
return v & 1u;
}
static uint8_t xor_checksum(const uint8_t *d, unsigned n)
{
uint8_t c = 0;
for (unsigned i = 0; i < n; i++) c ^= d[i];
return c;
}
int main(void)
{
uint8_t samples[] = { 0x00, 0x01, 0x03, 0x07, 0xFF, 0xA5 };
for (unsigned i = 0; i < sizeof samples; i++)
printf(“0x%02X parity bit = %u\n”, samples[i], parity_bit(samples[i]));
uint8_t frame[] = { 0x7E, 0x10, 0x20, 0x30 };
uint8_t sum = xor_checksum(frame, sizeof frame);
printf(“\nchecksum of frame = 0x%02X\n”, sum);
uint8_t with_sum[] = { 0x7E, 0x10, 0x20, 0x30, 0 };
with_sum[4] = sum;
printf(“checksum incl. the sum = 0x%02X (0 means the frame is intact)\n”, xor_checksum(with_sum, sizeof with_sum));
with_sum[2] ^= 0x04; /* flip one bit in transit */
printf(“after one flipped bit = 0x%02X (non-zero: error detected)\n”, xor_checksum(with_sum, sizeof with_sum));
return 0;
}
Output (verified by compiling and running)
0x00 parity bit = 0
0x01 parity bit = 1
0x03 parity bit = 0
0x07 parity bit = 1
0xFF parity bit = 0
0xA5 parity bit = 0
checksum of frame = 0x7E
checksum incl. the sum = 0x00 (0 means the frame is intact)
after one flipped bit = 0x04 (non-zero: error detected)
- Folding with
v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; collapses eight bits into the parity of all of them. - A single flipped bit always changes the XOR checksum, but two flips in the same bit position of different bytes cancel out. Real protocols use CRCs for stronger protection (Module 17).
Example 9: Signed Shifts Versus Division
Problem: Is x >> 1 the same as x / 2 for every integer? Compare them on positive and negative values.
signed_shift.c
#include <stdio.h>
int main(void)
{
int values[] = { 20, 7, 1, –1, –7, –20 };
printf(” x x>>1 x/2 x>>2 x/4\n”);
for (unsigned i = 0; i < sizeof values / sizeof values[0]; i++) {
int x = values[i];
printf(“%4d %5d %4d %5d %4d\n”, x, x >> 1, x / 2, x >> 2, x / 4);
}
return 0;
}
Output (verified by compiling and running)
x x>>1 x/2 x>>2 x/4
20 10 10 5 5
7 3 3 1 1
1 0 0 0 0
-1 -1 0 -1 0
-7 -4 -3 -2 -1
-20 -10 -10 -5 -5
| x | x >> 1 | x / 2 | Why they differ |
|---|
| 7 | 3 | 3 | same for non-negative values |
| -7 | -4 | -3 | >> rounds toward minus infinity, / truncates toward zero |
| -1 | -1 | 0 | arithmetic shift of all-ones stays all-ones |
For non-negative values the two agree. For negative values the shift floors the result while the division truncates, and the shift behavior itself is implementation-defined. Use / whenever the operand can be negative; use shifts only on unsigned types.
Example 10: Bytes of a Word, Shifts Versus Memory Order
Problem: Shifts and masks operate on the value, so they give the same result on every machine. Memory order depends on endianness. Show both, then swap the byte order as a network protocol requires.
endian_shifts.c
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint32_t word = 0x12345678;
uint8_t *p = (uint8_t *)&word;
printf(“value (arithmetic, never changes) : 0x%08X\n”, (unsigned)word);
printf(“byte at lowest address : 0x%02X\n”, p[0]);
printf(“(word >> 0) & 0xFF : 0x%02X\n”, (unsigned)(word & 0xFF));
printf(“(word >> 24) & 0xFF : 0x%02X\n”, (unsigned)((word >> 24) & 0xFF));
printf(“memory order, lowest address first : %02X %02X %02X %02X\n”, p[0], p[1], p[2], p[3]);
printf(“this machine is %s-endian\n”, p[0] == 0x78 ? “little” : “big”);
uint32_t swapped = ((word & 0x000000FFu) << 24) | ((word & 0x0000FF00u) << 8) | ((word & 0x00FF0000u) >> 8) | ((word & 0xFF000000u) >> 24);
printf(“byte-swapped : 0x%08X\n”, (unsigned)swapped);
printf(“__builtin_bswap32 : 0x%08X\n”, (unsigned)__builtin_bswap32(word));
return 0;
}
Output (verified by compiling and running)
value (arithmetic, never changes) : 0x12345678
byte at lowest address : 0x78
(word >> 0) & 0xFF : 0x78
(word >> 24) & 0xFF : 0x12
memory order, lowest address first : 78 56 34 12
this machine is little-endian
byte-swapped : 0x78563412
__builtin_bswap32 : 0x78563412
0x12345678 stored by a little-endian CPU (STM32F407 and x86)
lowest address first
On the STM32F407: The Cortex-M4 is little-endian in all STM32 devices: p[0] holds the least significant byte. Network protocols are big-endian, so multi-byte fields from a TCP/IP stack need byte-swapping (__builtin_bswap32 compiles to the single ARM instruction REV).
Example 11: Mini Exercises
Exercise 1: What is 0x5A & 0x0F?
0x0A.
Exercise 2: What is 0x5A | 0x0F?
0x5F.
Exercise 3: What is 0x5A ^ 0xFF?
0xA5 (every bit inverted).
Exercise 4: What is 0x01 << 5?
0x20 (32).
Exercise 5: What is 0x80 >> 3 for an unsigned byte?
0x10.
Exercise 6: Test whether a number is a multiple of 8 without %.
(x & 7) == 0.
Exercise 7: How many 1 bits are in 0xF0F0?
8.
Key Takeaways from the Bitwise Operators Examples
- The bitwise operators examples show AND as a mask, OR as a setter, XOR as a toggle or difference, and shifts as the way to position bits.
x & (x - 1) clears the lowest set bit: the basis of popcount and power-of-two tests.x & (N - 1) replaces x % N for unsigned x and N a power of two.- Pack fields with shift then OR; unpack with shift then mask:
(reg >> p) & ((1u << w) - 1). - XOR of all bytes detects any single-bit error and is zero if you include the checksum.
- Shifts act on values (portable); memory order is endianness-dependent.
- Use unsigned operands: signed right shift and
/ differ for negatives.
Ready for the quiz?
Next: compute-the-result questions, identify-the-operation exercises, MCQs and interview answers on bitwise operators.
1 Comment