Bit manipulation, told as one long night before a demo. Every chapter starts with a bug and ends with a tool you will keep.
The cast. Asha is a new firmware engineer. Ravi is the senior engineer who is going home early. The Sparrow is a greenhouse controller: a fan, a heater relay, a water pump, two LEDs and a buzzer, all run from registers on a small Cortex-M chip. The demo is at nine tomorrow morning.
The story, labs and exercises are the same in both. You can switch any time with the button at the top.
binary and hexadecimalBinary writes a number using only 0 and 1, one digit per switch. Hexadecimal (hex) writes it in base 16 using 0 to 9 and A to F, where one hex digit stands for exactly four bits.
Registers are rows of bits, and a row of 32 zeros and ones is unreadable. Hex squeezes four bits into one character, so you can read a register at a glance.
Eight light switches written out as on and off is 10100101: tiring to read and easy to get wrong. Cut it into two groups of four and give each group one name (1010 is A, 0101 is 5). Now you just say A5, like reading a number plate instead of spelling out every stroke.
Misreading register values, and adding up binary digits by hand with no way to check.
0xA5 = 1010 0101
A 5
0xFF = 1111 1111 (all eight switches on)
0x0F = 0000 1111 (only the lower four on)0xA5The 0x at the front means 'this is written in hex'.1010 0101The same value as eight switches, split into two groups of four.A 5Each group of four is one hex digit: 1010 is A and 0101 is 5.0xFF, 0x0FHandy patterns: all on, and only the lower four on.A bit is one switch: 0 or 1. Eight bits make a byte. Four bits make a nibble. A chip's natural chunk is a word: 32 bits on a Cortex-M.
Bits are numbered from the right, starting at 0. Bit 0 is the least significant bit (LSB) and is worth 1. The leftmost bit is the most significant bit (MSB). Bit n is worth 2n. Datasheets and code both use this numbering, so get comfortable with it.
Hex exists because binary is hard to read. One hex digit is exactly one nibble, so you can convert by looking at four bits at a time, with no arithmetic.
| bin | hex | bin | hex | bin | hex | bin | hex |
|---|---|---|---|---|---|---|---|
| 0000 | 0 | 0100 | 4 | 1000 | 8 | 1100 | C |
| 0001 | 1 | 0101 | 5 | 1001 | 9 | 1101 | D |
| 0010 | 2 | 0110 | 6 | 1010 | A | 1110 | E |
| 0011 | 3 | 0111 | 7 | 1011 | B | 1111 | F |
1011 0100 in hex?0x in front of a number means it is written in hex. To read hex like 0xB4: B is 1011 and 4 is 0100, so the bits are 1011 0100.0xC8. So where did the minus come from? To answer it she needs three things: how a chip stores a negative number, why the chip stores it that way, and how to tell if a number is negative.two's complementThe way computers store negative whole numbers. A signed byte uses the same 8 bits as an unsigned one, but the top bit counts as negative, so the values run from -128 to 127 instead of 0 to 255.
The adding circuit then works for positive and negative numbers alike. It also explains why one byte can mean two different things depending on how you read it.
A car's trip meter that shows only three digits. Wind it back one step from 000 and it shows 999. Computers treat that 999 as 'minus one'. A byte works the same way: one step below 0 is 255, which a signed byte reads as -1.
A sensor sends the byte 200 and the log prints -56 lux: the bits are right and the code read them as signed.
uint8_t u = 200; /* 1100 1000 read as unsigned: 200 */ int8_t s = (int8_t)u; /* the same bits read as signed: -56 */
uint8_t u = 200;An unsigned byte: all eight bits count upwards, 0 to 255.int8_t s = (int8_t)u;The same eight bits, but now the top bit is worth -128.-56200 - 256 = -56. Nothing in the memory changed: only how it is read.~x + 1, which equals 2n - x. It has one zero, one adder for signed and unsigned, and the top bit doubles as the sign. The range is lopsided, so negating the most negative value overflows. Widening sign-extends signed types and zero-extends unsigned ones. The labs below let you check any of it quickly.A byte is eight switches. Each one is on (1) or off (0). The hardware has no "minus sign" switch. So to store -5 we have to agree on a code: a rule that says which switch patterns mean which numbers.
The simplest code is for positive numbers only. This is called unsigned. Each switch that is on adds its weight. From the left, the weights are 128, 64, 32, 16, 8, 4, 2, 1. So 0000 0101 is 4 + 1 = 5, and 1100 1000 is 128 + 64 + 8 = 200.
Three codes have been tried. Only one survived.
Attempt A: sign and magnitude. Use the leftmost switch as the sign (0 means plus, 1 means minus) and the other seven for the size. So +5 is 0000 0101 and -5 is 1000 0101. It is easy to read, but it has two problems:
0000 0000 (+0) and 1000 0000 (-0).1000 1010, which reads as -10. The chip would need extra circuits to look at the signs first.Attempt B: one's complement. To make -5, flip every bit of +5: 0000 0101 becomes 1111 1010. Better, but there are still two zeros (0000 0000 and 1111 1111), and addition needs a special fix-up step.
Attempt C: two's complement. To make -5, flip every bit and then add 1: 1111 1010 + 1 = 1111 1011. Now there is one zero, and plain addition just works. 0000 0101 + 1111 1011 gives 1 0000 0000. A byte only has eight bits, so the leading 1 falls off and 0000 0000 is left. That is 5 + (-5) = 0.
Sign-magnitude and one's complement both have a +0 and a -0 and need special-case adders. Two's complement removes both problems: -x = ~x + 1.
1111 1111 mean as a signed byte?0000 0000. Add 1: 0000 0001, which is 1. So the number is -1. Check: 1 + (-1) = 0000 0001 + 1111 1111 = 1 0000 0000, and the carry falls off, leaving 0.Eight bits give 256 patterns, 0 to 255. Picture a clock face with 256 positions. Go past 255 and you wrap to 0, like 12 o'clock after 11. Walk backwards from 0 and you land on 255. So 255 can stand for -1, 254 for -2, and so on.
The rule is: the number -x is stored as 256 - x. For -56 that is 256 - 56 = 200, which is 1100 1000. And "flip the bits, add 1" is just a quick way to compute it: flipping every bit of x gives 255 - x (255 is eight 1s), and adding 1 gives 256 - x.
Because -x is congruent to 2n - x modulo 2n, add, subtract and compare all share one datapath and the carry out is simply ignored. Signed overflow shows up when the carry into the sign bit differs from the carry out of it (the V flag).
Now see subtraction turn into addition:
Try A = 3 and B = 5. The answer comes out as 1111 1110. The leftmost bit is 1, so it is negative, and it is -2, which is right.
How to use the lab. Type 56 and look at the bits. Then type -56. The "How" section shows +56 being flipped and incremented into -56. Try 127 and press +1: it wraps to -128, like the clock passing 255.
| Type | Bits | Unsigned range | Signed range |
|---|---|---|---|
| uint8_t / int8_t | 8 | 0 to 255 | -128 to 127 |
| uint16_t / int16_t | 16 | 0 to 65,535 | -32,768 to 32,767 |
| uint32_t / int32_t | 32 | 0 to 4,294,967,295 | -2,147,483,648 to 2,147,483,647 |
INT_MIN in 32 bits. Negating or taking abs() of the most negative number overflows. Wrapping is safe for unsigned types, but for signed types in C it is undefined behaviour.Look at the leftmost bit. It is called the sign bit: bit 7 of a byte, bit 15 of a 16-bit value, bit 31 of a 32-bit value. 1 means negative. 0 means zero or positive. Careful: zero also has a 0 in front, but zero is not positive. So "positive" means the sign bit is 0 and the value is not zero.
x < 0, x > 0, x == 0. The compiler turns this into the cheapest sign check. This is the normal answer.(x & 0x80u) != 0 for a byte, or (x >> 31) & 1u for 32 bits.(int8_t)x < 0 reads the same bits as signed, then compares.How big is a negative number? Say you see 1111 1011 in a debugger. To find its value: flip all the bits (0000 0100), add 1 (0000 0101, which is 5), and put a minus in front. It is -5. The checker above shows these steps for any negative number.
x < 0 is always false for uint8_t (the compiler warns). Right-shifting a negative signed value is implementation-defined in ISO C. GCC, Clang and the Arm compilers copy the sign bit, so x >> 31 gives -1 or 0 there, while the same on an unsigned value is fully defined and gives 1 or 0. Prefer unsigned types for bit work. And never assume a byte from a sensor is signed: the byte 0xC8 is 200 or -56 depending only on the type you gave it.x < 0 reduces to a check of the sign bit (the N flag after a flag-setting instruction on ARM). (x > 0) - (x < 0) gives the sign as -1, 0 or 1 without a branch. Right-shifting a negative signed value is implementation-defined in C, but arithmetic on every compiler you will meet.When you put a byte into a bigger box (8 bits into 32), the chip must fill the new bits on the left. To keep the same number, it fills differently for each reading:
0xC8 becomes 0x000000C8, still 200.0xC8 becomes 0xFFFFFFC8, still -56. Filling with zeros here would turn -56 into +200.That is Asha's bug. The sensor meant 200. Her code stored it in an int8_t, so the chip read the top bit as a sign and printed -56.
int8_t x = (int8_t)0xC8; int y = x; What is y?uint8_t.char may be signed or unsigned, depending on the compiler and the chip. Never use it for raw data. Use uint8_t for bytes and bit patterns, and use signed types only for real quantities that can be negative.char is unsigned by default on ARM (the ARM EABI) but signed on x86, so the same code can behave differently on the host and on the target. Loads come in signed and unsigned forms (LDRSB versus LDRB), and SXTB/UXTB extend a register in place. Integer promotion then turns small types into int before any arithmetic.bitwise operators (AND, OR, XOR, NOT)Operators that work on each bit separately. AND (&) keeps a bit only if both are 1. OR (|) keeps it if either is 1. XOR (^) keeps it if they differ. NOT (~) flips every bit.
Firmware controls hardware one bit at a time. These operators let you pick out, set, clear or flip single bits without touching the rest of the register.
A panel of eight switches and a cardboard stencil with holes in it. AND: look only at the switches showing through the holes. OR: switch on everything under a hole and leave the rest alone. XOR: flip everything under a hole. NOT: flip every switch on the panel.
Using the wrong operator (a single & where you meant &&) gives bugs that compile cleanly and misbehave quietly.
0xA5 & 0x0F = 0x05 /* keep only the lower four bits */ 0xA5 | 0x0F = 0xAF /* force the lower four bits on */ 0xA5 ^ 0xFF = 0x5A /* flip every bit */ ~0x0F = 0xF0 /* NOT: swap zeros and ones */
0xA5 & 0x0FAND with a mask keeps the bits where the mask is 1 and clears the rest: 1010 0101 becomes 0000 0101.0xA5 | 0x0FOR turns on every bit that is on in the mask: the lower four become 1111.0xA5 ^ 0xFFXOR with all ones flips every bit.~0x0FNOT flips every bit of the value itself.| Operator | Name | Its job | Rule, bit by bit |
|---|---|---|---|
a & b | AND | Keep or clear. Used with a mask. | 1 only if both are 1 |
a | b | OR | Force on. Sets bits. | 1 if either is 1 |
a ^ b | XOR | Flip or compare. | 1 if the bits differ |
~a | NOT | Invert everything. | 0 becomes 1, 1 becomes 0 |
a << n | Shift left | Multiply by 2n, or move a field up. | Bits move left, zeros come in |
a >> n | Shift right | Divide by 2n, or move a field down. | Bits move right |
& and && are different. So are | and ||. 0x02 && 0x04 is true (1). 0x02 & 0x04 is 0.== binds tighter than &, ^ and |. So x & 1 == 0 means x & (1 == 0), which is always 0. Write (x & 1) == 0. Put parentheses around every bit operation inside a comparison.1100 and B = 1010: A AND B = 1000, A OR B = 1110, A XOR B = 0110, and NOT A = 0011.int are promoted before the operator runs, so ~x on a uint8_t gives a negative int. Cast the result. ARM has a dedicated BIC (bit clear) instruction, so x & ~m compiles to a single operation. Compound forms like ^= on a volatile register are still a read-modify-write, not an atomic operation.CTRL = HEATER;. The heater clicks on. The fan, which was running a second ago, stops. She did not write a single thing about the fan.set, clear and toggle a bitChanging one bit of a register without disturbing the others. Set uses OR with a mask, clear uses AND with an inverted mask, and toggle uses XOR.
A single register often controls several things at once (a heater, a fan, an alarm). Writing the whole register would turn the others off.
A hostel light panel where each switch belongs to a different room. You want your own light on. Flipping just your switch is right. Pressing 'all off, then mine on' plunges every other room into darkness.
Writing CTRL = HEATER; turns the heater on and quietly switches the fan off.
#define HEATER (1u << 3) CTRL |= HEATER; /* set: heater on */ CTRL &= ~HEATER; /* clear: heater off */ CTRL ^= HEATER; /* toggle: flip it */
1u << 3A mask with only bit 3 on: 0000 1000.CTRL |= HEATER;OR turns bit 3 on and leaves every other bit as it was.CTRL &= ~HEATER;~HEATER has every bit on except bit 3; AND clears just that one.CTRL ^= HEATER;XOR flips bit 3 each time it runs.Assignment writes all eight bits at once. To change one bit and leave the others alone, you use a mask: a number that has a 1 only at the bit you care about. Think of it as a stencil laid over the register.
| Goal | C | Why it works |
|---|---|---|
| Set bit n | x |= (1u << n); | OR with 1 forces on. OR with 0 changes nothing. |
| Clear bit n | x &= ~(1u << n); | The inverted mask has a 0 at n and 1 everywhere else. AND keeps the rest. |
| Toggle bit n | x ^= (1u << n); | XOR with 1 flips. XOR with 0 changes nothing. |
| Test bit n | (x & (1u << n)) != 0 | AND isolates the bit. Non-zero means it was set. |
| Several bits at once | x |= (FAN | PUMP); and x &= ~(FAN | PUMP); | Build the mask by OR-ing named bits. |
| Any of these set? | (x & M) != 0 | Some overlap. |
| All of these set? | (x & M) == M | Every mask bit is present. |
#define HEATER (1u << 1) or an enum and the code reads like English: CTRL |= HEATER;.1u, not 1. A plain 1 is a signed int, and 1 << 31 is undefined behaviour. For a 64-bit mask use 1ull.0000 0001, the mask is 0000 1000, and OR gives 0000 1001.BIT(n) and per-field _Pos/_Msk pairs, over magic numbers. Test for "all of these" with (x & m) == m, not x & m. Some Cortex-M3/M4 parts have bit-band alias regions that turn a single-bit write into an atomic operation, but many parts (such as M0/M0+) do not, so check the core's reference manual.register field (mask and shift)A setting that takes several bits of a register (for example a 3-bit speed value in bits 4 to 6). To read it you mask the other bits away and shift it down to the right; to write it you clear the old bits and shift the new value into place.
Hardware packs many small settings into one register to save space, so almost every driver does this.
A date written as one long number, 05102026. To read the month you ignore the first two digits and the last four, and read the two in the middle. Reading a register field is the same: cover the bits you do not want, then slide the rest down.
Writing a field without clearing it first leaves the old bits behind, so the new value is OR-ed with the old one.
/* speed field: bits 4 to 6 */
uint32_t get_speed(uint32_t reg) { return (reg >> 4) & 0x7; }
uint32_t set_speed(uint32_t reg, uint32_t v) {
return (reg & ~(0x7u << 4)) | ((v & 0x7u) << 4);
}(reg >> 4) & 0x7Shift bit 4 down to position 0, then keep only three bits (0x7 is 0b111).reg & ~(0x7u << 4)Clear the old three bits first.(v & 0x7u) << 4Take the new value, keep three bits, and move it into place.| ...OR joins the cleared register with the new field.A field is a run of neighbouring bits treated as one small number. The datasheet notation [6:4] means "from bit 6 down to bit 4", so position 4, width 3.
((1u << width) - 1u) << pos(reg >> pos) & ((1u << width) - 1u)reg = (reg & ~mask) | ((val << pos) & mask);0xB6C5?(1u << 32) is undefined behaviour. A generic get_field must special-case a width of 32.FIELD_Pos and FIELD_Msk. The macros are the same two ideas: shift and mask. Exercise 2 makes you write get_field, set_field and reg_update.get_field and set_field with constant arguments often compile to a single instruction. Linux's GENMASK(h, l) and FIELD_GET/FIELD_PREP are the same idea in macro form. If a field is also write-1-to-clear or has side effects on read, a plain read-modify-write is wrong (see Chapter 5).CTRL |= HEATER;. It is one line. How can one line lose a bit?read-modify-writeChanging part of a register takes three steps: read the whole value, change the bit you want, and write the whole value back. The line CTRL |= BIT hides all three.
Between the read and the write something else can change the register, for example an interrupt. Your write then undoes that change.
Two flatmates share a grocery list on the fridge. You photograph it, add 'milk' at your desk, then rewrite the list from your photo. Meanwhile your flatmate crossed off 'eggs'. Your rewrite brings the eggs back: their change is lost.
The 'phantom alarm': an interrupt sets a flag bit in the middle of your update, and your write erases it, so the alarm is lost or appears from nowhere.
CTRL |= HEATER; /* what the chip really does: */ /* 1. read CTRL into a register */ /* 2. OR in the HEATER bit */ /* 3. write the result back */
1. readCopy the whole register into the CPU.2. OR in the bitChange the copy.3. write backStore the whole copy. If an interrupt changed CTRL between steps 1 and 3, that change is overwritten.The cures are in Lesson 24: make the update indivisible, give the register one writer, or switch interrupts off for those three steps.
On a microcontroller, CTRL is a memory-mapped register: a location at a fixed address that is wired to hardware. You declare it with volatile:
volatile tells the compiler: every read and every write here is a real event. Do not cache it, merge it, reorder it or delete it. Without it, while (!(STATUS & READY)) {} can be compiled into an infinite loop that reads STATUS once.
CTRL |= HEATER; looks like one operation. It is three: read the register, modify a copy, write it back. An interrupt that lands between the read and the write gets its change overwritten. This is called a lost update, and it is one of the most common real firmware bugs.
Some status flags are write-1-to-clear (W1C). You clear a flag by writing a 1 to its bit. Writing 0 does nothing. Now think about what STATUS |= RXNE; does. It reads every flag that is currently set, ORs in RXNE, and writes the whole thing back. That writes a 1 to every set flag, so it clears all of them, including the ones you never looked at.
x |= 1 atomic?". The expected answers are the ones on this page.volatile tells the compiler: always do a real read or write, every time. And |= is really three steps (read, change, write back), so something can sneak in between them.volatile only orders accesses relative to other volatile accesses. It is not atomic, and it does not stop the CPU or write buffers from reordering, so some peripheral sequences need DMB or DSB (and an ISB after changing certain system registers). Cores with LDREX/STREX (M3 and up) can build an atomic read-modify-write on normal memory. M0/M0+ cannot, so they disable interrupts instead. Prefer BASEPRI over a full PRIMASK disable when you only need to block lower-priority interrupts.value << 2 to get more resolution. At night it is fine. In bright light, the value wraps to something tiny. Then she tries to halve a negative offset with >> 1 and gets an answer she did not expect.shifts (<< and >>)Moving every bit of a number to the left or right. x << n shifts left by n places, which multiplies by 2n. x >> n shifts right, which divides by 2n, throwing away the bits that fall off the end.
Shifts build masks (1u << 3), pull fields out of registers, and do fast multiplication and division by powers of two.
Put a zero on the end of a normal number and it becomes ten times bigger: 25 becomes 250. In binary, shifting left puts a zero on the end, so it doubles the number. Shifting right chops the last digit off, so it halves it.
Shifting a signed number to the left, or shifting by 32 or more places on a 32-bit value, is undefined behaviour in C: the compiler may do anything. Always shift unsigned values by less than the width.
uint32_t a = 1u << 3; /* 0000 1000 = 8 */ uint32_t b = 0xA5u >> 4; /* 0000 1010 = 0xA */
1u << 3The 1 moves three places left, giving 8. The u means unsigned, which keeps the shift well defined.0xA5u >> 4Moves the top four bits (1010) down to the bottom, throwing the lower four away.x << n multiplies by 2n. Bits that move off the top are lost.x >> n on an unsigned value divides by 2n. Zeros come in at the top. This is a logical shift.x >> n on a signed negative value usually copies the sign bit in at the top. This is an arithmetic shift. The C standard calls it implementation-defined, but every common embedded compiler does it this way.-7 >> 1 is -4, but -7 / 2 is -3.x << 32 on a 32-bit value.1 << 31 is the famous one.In C, anything smaller than int is promoted to int before an operator runs. So with uint8_t x = 0xF0;, the expression ~x is computed on a 32-bit int: ~0x000000F0 = 0xFFFFFF0F, which is -241. It is not 0x0F. Cast the result back: (uint8_t)~x.
The same promotion means uint8_t a = 200, b = 100; a + b is 300, not 44. The result only wraps if you store it in a uint8_t again.
-8 >> 1 give?(x << n) | (x >> (32 - n)) is undefined when n is 0, because it shifts by 32. The masked version above avoids that.x * 10 when you mean multiply. The compiler already turns constant multiplies into shifts and adds. Use shifts when you are moving bit fields, not when you are doing arithmetic.1u, never shift by the full width, and do not shift negative numbers left.-fsanitize=undefined: it flags bad shift counts and signed overflow. GCC and Clang recognise the masked rotate idiom and emit a single ROR. __builtin_clz and __builtin_ctz are undefined for 0, so guard the call. They are GCC and Clang extensions, not ISO C. Cortex-M3, M4 and M7 have a CLZ instruction (ctz is RBIT then CLZ); Cortex-M0 and M0+ have neither, so the compiler calls a slower library routine. The portable binary-search version in this lesson depends on nothing. Because the compiler assumes signed overflow never happens, a loop that relies on it wrapping can be optimised into something you did not write.clearing the lowest set bit (the power-of-two trick)The expression x & (x - 1) clears the lowest 1 bit of x. Subtracting 1 turns the lowest 1 into 0 and every 0 below it into 1, so AND-ing wipes out just that bit.
Three useful tricks come from it: testing for a power of two, counting the 1 bits, and finding the lowest set bit (x & -x).
Crossing names off a guest list, always the lowest name first, and counting as you go. When the list is empty, your count is the number of guests. Each x &= x - 1 crosses off the lowest 1 bit, so the loop runs once per 1 bit.
Writing slow loops over all 32 bits when two instructions would do, or calling a count-trailing-zeros builtin on 0, which is undefined.
int is_pow2(uint32_t x) { return x && !(x & (x - 1)); }
int popcount(uint32_t x) {
int n = 0;
while (x) { x &= x - 1; n++; } /* one 1 bit removed per loop */
return n;
}x & (x - 1)Removes the lowest set bit: 1100 becomes 1000.!(x & (x - 1))A power of two has exactly one 1 bit, so after removing it nothing is left: zero.x &= x - 1; n++;Remove a bit and count it. The loop runs once per 1 bit, not 32 times.Take 0110 1000. Subtract 1 and you get 0110 0111. The lowest 1 became 0, and all the zeros below it became 1s. Everything above is untouched. Almost every trick below follows from that one picture.
| Trick | Code | What it gives you |
|---|---|---|
| Clear the lowest set bit | x & (x - 1) | Drops exactly one 1 bit |
| Isolate the lowest set bit | x & -x | A mask with only that bit |
| Is it a power of two? | x != 0 && (x & (x - 1)) == 0 | A power of two has a single 1 bit. Do not forget the x != 0. |
| Count set bits (popcount) | while (x) { x &= x - 1; c++; } | Loops once per 1 bit (Kernighan) |
| Parity | x ^= x >> 16; x ^= x >> 8; ... | Fold with XOR. Bit 0 is the parity. |
| Index of lowest set bit | __builtin_ctz(x) | Count trailing zeros. x must not be 0. |
| Index of highest set bit | 31 - __builtin_clz(x) | Count leading zeros. Cortex-M3 and up have a CLZ instruction. |
| Lowest zero bit | ~x & (x + 1) | A mask with only the first free slot |
| Round up to a power of two | x--; x |= x >> 1; x |= x >> 2; ... x++; | "Smear" the top bit downwards, then add 1 |
| Align up | (x + a - 1) & ~(a - 1) | Next multiple of a (a is a power of two) |
| Align down | x & ~(a - 1) | Previous multiple of a |
| Is it aligned? | (x & (a - 1)) == 0 | Low bits are zero |
| Modulo a power of two | x & (n - 1) | Same as x % n for unsigned, without a divide. Ring buffer wrap. |
| Average without overflow | (a & b) + ((a ^ b) >> 1) | No 33rd bit needed |
head & (SIZE - 1). DMA and cache code aligns buffers with align_up. Allocators round requests to powers of two. Exercises 3 and 4 cover all of this.0110 1000 minus 1, which is 0110 0111. AND the two together and you get 0110 0000. The lowest 1 is gone. Try the lab and read the trace line by line.__builtin_popcount calls a library routine or a table, and the SWAR version is often a good fit when you cannot afford a table. M3 and up have CLZ and RBIT, so ctz(x) is clz(rbit(x)) in two instructions. M0/M0+ have neither. For ring buffers, a power-of-two size lets you replace modulo with a mask. Keep head and tail as free-running counters and apply the mask only when indexing, so "full" and "empty" stay distinguishable without a spare slot.0x12345678. The gateway shows 0x78563412. All four bytes arrived. They arrived in the wrong order.endianness (byte order)The order in which the bytes of a multi-byte number are stored in memory. Little-endian stores the smallest byte first, which is what Arm Cortex-M chips do. Big-endian stores the biggest byte first, which is what most network protocols use.
When two devices exchange numbers they must agree on the order, or each will read the other's numbers scrambled.
Writing a date as 04/10 or 10/04. Some countries write the day first, others the month. The facts are identical, but a reader expecting the other order turns up on the wrong day. Two chips with different byte orders misread each other's numbers in exactly this way.
A temperature of 0x1234 sent from a little-endian chip arrives as 0x3412 on a reader that assumes big-endian.
uint32_t v = 0x12345678; /* little-endian memory, lowest address first: */ /* 78 56 34 12 */
0x12345678A four-byte number. The biggest byte is 0x12 and the smallest is 0x78.78 56 34 12How a little-endian chip stores it: smallest byte at the lowest address.(a network)Would send 12 34 56 78. Convert explicitly rather than trusting both sides to agree.A 32-bit value occupies four bytes in memory. Endianness is which byte sits at the lowest address.
This works on every chip. Shifts describe the value, so they do not depend on endianness. The cast to uint32_t before the shift matters: a uint8_t is promoted to int, and 0xFF << 24 overflows a signed int.
uint32_t v = 0x12345678; is stored at address 0x2000. What byte is at 0x2000?*(uint32_t *)buf on a byte buffer breaks two ways. It may be misaligned (a hard fault on Cortex-M0), and it breaks strict aliasing rules. Use shifts, or memcpy into a variable.htons, htonl, ntohs, ntohl convert between host and network order. __builtin_bswap32 maps to the ARM REV instruction. Exercise 6 makes you write bswap16, bswap32 and the load helpers by hand.12-03-2026 and 2026-03-12 hold the same information in a different order. Bytes work the same way: the value is the same, only the order in memory differs. When two systems disagree on the order, each one reads the other's bytes backwards.htonl and ntohl compile down to a REV instruction. Unaligned access differs by core: M0/M0+ fault on any unaligned load or store, while M3 and up allow unaligned LDR/STR but still fault on multi-register forms (LDM, LDRD), and a configuration bit can trap all unaligned accesses. Check your core's reference manual. Struct and bitfield layout also depend on the ABI, which is why wire formats should be built with explicit shifts.malloc is fragmenting the 2 KB heap. After a few hours the Sparrow runs out of memory while half of it is free. Ravi's old trick: if every buffer is the same size, you do not need a heap at all. You need a list of which slots are taken. One bit per slot.bitmapA row of bits where each bit stands for one thing: bit 5 is 1 if block 5 is in use and 0 if it is free.
It tracks 32 items in a single 32-bit number, and finding or changing one takes a couple of instructions. In firmware it can replace malloc.
The seat map when you book a cinema ticket: one small square per seat, green for free and grey for taken. One glance shows every seat. A bitmap is that seat map with one bit per block.
Using the heap for small fixed-size blocks can fragment and fail unpredictably, which a bitmap never does.
uint32_t used = 0; /* all 32 blocks free */ used |= (1u << 5); /* mark block 5 in use */ used &= ~(1u << 5); /* free block 5 */ int taken = (used >> 5) & 1u; /* is block 5 in use? */
uint32_t used = 0;One bit per block, all zero meaning every block is free.used |= (1u << 5);Allocate: turn bit 5 on.used &= ~(1u << 5);Free: turn bit 5 off.(used >> 5) & 1uTest: move bit 5 down to position 0 and keep just that bit.A bitmap stores one yes/no fact per item, packed 32 to a word. Here, bit i = 1 means block i is in use. To allocate, find the first 0. To free, clear the bit.
The first free slot is ~bm & (bm + 1): a mask with only the lowest zero of bm turned on. Convert the single-bit mask to an index with __builtin_ctz. No loop is needed.
| Set operation | Code |
|---|---|
| Add item i | s |= 1u << i |
| Remove item i | s &= ~(1u << i) |
| Is item i in the set? | (s >> i) & 1u |
| Union / intersection | a | b and a & b |
| Difference (in a, not in b) | a & ~b |
| Is a a subset of b? | (a & b) == a |
| Size of the set | popcount |
| Bigger than 32 items | word = i >> 5, bit = i & 31 |
ready = 0b0010 1100. Higher number means higher priority. Which priority runs?31 - clz(ready). This is how the optimised FreeRTOS port selects the next task.XOR (exclusive or)A bit operation that gives 1 when its two inputs differ and 0 when they are the same. Two useful facts follow: x ^ x = 0, and x ^ 0 = x.
XOR undoes itself: apply it twice with the same value and you get the original back. That powers toggling, simple parity and checksums, and finding the one value that has no partner in a list.
A staircase light with one switch at the bottom and one at the top. Flip either switch and the light changes; flip the same one again and it changes back. The light is on exactly when the two switches disagree. That is XOR.
Missing that XOR-ing every value in a list cancels all the pairs, so the one unpaired value is left: a classic interview problem solved in one line.
int single(const int *a, int n) {
int r = 0;
for (int i = 0; i < n; i++) r ^= a[i]; /* pairs cancel out */
return r;
}int r = 0;Start from zero, because x ^ 0 = x.r ^= a[i];Fold every value in. A value that appears twice cancels itself (x ^ x = 0).return r;Whatever is left is the one value that appeared an odd number of times.Three facts make XOR special:
a ^ a = 0: a value cancels itself.a ^ 0 = a: zero does nothing.a ^ b ^ a = b.XOR all the values together. Every pair cancels. The odd one is left. One loop, one variable.
a == b first. In real code, a temporary variable is clearer and just as fast, so this is an interview classic rather than a practical tool.a ^ b has a 1 exactly where a and b differ. Popcount of it is the Hamming distance.n ^ (n >> 1). Neighbouring numbers differ by exactly one bit, so a rotary encoder or a clock-crossing counter can never show a wildly wrong value in transit.The standard check string 123456789 must give 0xF4. If your code gives that, it is right.
Packing is fields (Chapter 4) plus a layout decision. Pick the widths, pick the positions, and keep them written down in one table.
C bitfields look convenient, but the standard leaves the layout to the compiler: which end of the word the first field goes in, how fields pack, and padding. Endianness can reverse it. Do not use bitfields for wire formats or for registers you share between toolchains. Use explicit shifts and masks. They mean the same thing everywhere.
Small numbers are common and large numbers are rare, so spend fewer bytes on small ones. A varint (LEB128) stores 7 data bits per byte and uses the top bit to say "more bytes follow".
packed belong to the next lesson.__attribute__((packed)) removes padding but invites unaligned accesses that fault on some cores. Signed values in varints are usually zigzag-encoded so that small negatives stay small. Always document the bit order and byte order of a wire format, and test it against known vectors.uint8_t x = 0xF0; printf("%d", ~x);if (-1 < 1u) puts("yes"); else puts("no");int x = 4; if (x & 1 == 0) puts("even");x & 0, which is 0 (false) for every x. Write (x & 1) == 0.uint8_t a = 200, b = 100; int s = a + b; What is s?(uint8_t)(a + b) gives 44.uint32_t n = 0; if (n & (n - 1)) ... else ... as a power-of-two test for n = 0n != 0.uint16_t h = 0x8000; uint16_t r = h << 1; int t = h << 1; What are r and t?uint32_t mask = 1 << 31; is...1u << 31.int8_t c = -128; int8_t d = -c; What is d?INT_MIN for int, where negation is undefined behaviour.| Problem | The idea | Time, space |
|---|---|---|
| Single Number (I) | XOR everything | O(n), O(1) |
| Single Number (II, others appear 3 times) | Two accumulators, ones and twos | O(n), O(1) |
| Single Number (III, two singles) | XOR gives a^b. Split by any set bit of it | O(n), O(1) |
| Missing Number | XOR indices with values | O(n), O(1) |
| Number of 1 Bits | x &= x - 1 loop | O(set bits) |
| Counting Bits (0..n) | out[i] = out[i >> 1] + (i & 1) | O(n) |
| Reverse Bits | Shift result left, feed it the lowest bit | O(32) |
| Power of Two / Power of Four | One bit set; for four also & 0x55555555 | O(1) |
| Hamming Distance | popcount of a ^ b | O(1) |
| Total Hamming Distance | Per bit: ones × zeros | O(32n) |
| Sum of Two Integers | XOR is sum, AND shifted is carry. Repeat. | O(32) |
| Bitwise AND of a Range | Keep the common prefix of m and n | O(32) |
| Subsets | Every mask 0..2n-1 is a subset | O(n · 2n) |
| Gray Code | i ^ (i >> 1) | O(2n) |
x & (x-1) clears the lowest 1; x & -x isolates it; ~x & (x+1) isolates the lowest 0; x | (x-1) sets the trailing zeros; (x + a - 1) & ~(a - 1) aligns up; a signed right shift is arithmetic on every common compiler but implementation-defined; and a shift count must be less than the width.You have met every idea. Start the timer and commit to ten minutes. The real practice is in the exercises download: exercises/02-bit-manipulation/, run with make test L=02.
Retype the field helpers. Spaces and line breaks do not matter.
int popcount32(uint32_t x) {
int c = 0;
while (x) { x (x - 1u); c++; }
return c;
}
bool is_pow2(uint32_t x) {
return x && (x & (x - 1u)) == 0;
}
uint32_t align_up(uint32_t x, uint32_t a) {
return (x + a - 1u) & ;
}
uint32_t lowest_bit(uint32_t x) {
return x & ;
}
Write set_field(reg, pos, width, val) in a blank box. Then reveal the answer and be honest.
Try each for ten minutes before opening the hint. The exercises download has tests for the ones marked "in the exercises".
Every value appears three times except one. Find it in O(n) time and O(1) space.
XOR alone cancels pairs, not triples. Keep two variables, ones and twos, that track bits seen once and bits seen twice. A bit seen a third time clears from both.
XOR adds without the carry. AND, shifted left by one, is the carry. Repeat until the carry is 0.
Between m and n every lower bit flips at some point, so it ends up 0. Only the common prefix survives.
A power of two, and the single set bit must be at an even position. Which mask selects the even positions?
For n items there are 2n subsets. Each number from 0 to 2n-1 picks items by its set bits.
Do not compare every pair. Look at one bit position at a time. If k numbers have a 1 there, then k × (n - k) pairs differ at that bit.
Binary search on the answer: test the low 16 bits, then 8, then 4, then 2, then 1.
A small RTOS keeps one bit per priority in a 32-bit word: bit p is 1 when a task of priority p is ready. Write make_ready, make_idle and highest_ready, which finds the best task to run in one instruction instead of a loop over 32 tasks.
The index of the highest set bit is 31 - __builtin_clz(x). Both clz and ctz are undefined for 0, so test for an empty word first and return -1.
Exercises 1 to 12 in exercises/02-bit-manipulation/: bit_ops, field, popcount, pow2_align, reverse_bits, byteorder, xor_tricks (including Single Number III), bitmap, crc8, gray, count_bits, readymap (a ready bitmap with clz and ctz, portable fallbacks and a round-robin pick).
Answer from memory. Retake it on the review dates it gives you.
| You want to | Write |
|---|---|
| Set / clear / toggle bit n | x |= 1u<<n x &= ~(1u<<n) x ^= 1u<<n |
| Test bit n | (x >> n) & 1u |
| Field mask | ((1u<<w)-1u)<<pos (handle w = 32) |
| Extract / insert field | (r>>pos)&m (r&~(m<<pos))|((v&m)<<pos) |
| Negate (two's complement) | ~x + 1 |
| Clear lowest 1 / isolate lowest 1 | x & (x-1) x & -x |
| Power of two | x && !(x & (x-1)) |
| Align up / down | (x+a-1)&~(a-1) x&~(a-1) |
| x mod 2k | x & ((1u<<k)-1u) |
| First free slot in a bitmap | ~bm & (bm+1) then ctz |
| Highest set bit | 31 - clz(x) |
| Differences between a and b | a ^ b (popcount = Hamming distance) |
| Byte order | Build values with shifts. Never cast byte pointers. |
| Gray code | n ^ (n>>1) |
1u (or 1ull), never 1, when building masks.int types are promoted to int: cast after ~, and cast bytes to uint32_t before shifting left.volatile for hardware registers, every time.x & (x - 1) == 0 says 0 is a power of two. Add x != 0.