Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Embedded C Practice Problems with Solutions

Practice embedded C with worked problems: bit manipulation, register fields, endianness, struct packing, integer promotion traps, fixed-point math and saturating arithmetic, plus challenges and interview questions.

Embedded programming rewards fluency in a small set of low-level skills: manipulating bits and register fields, knowing how integers behave when they are narrow, understanding memory layout, and doing math without a floating-point unit. These are also the topics that embedded interviews and code reviews focus on. This lesson collects the most useful ones as worked problems that you can run, followed by challenges to solve on your own and a list of questions to think through.

Try each problem yourself before looking at the solution. The runnable examples print their results so you can check your reasoning.

Part 1: bit manipulation toolkit

Problems.

  1. Write macros to set, clear, toggle and test bit n of a register.
  2. Count the set bits in a 32-bit word, without a lookup table.
  3. Test whether a number is a power of two in one expression.
  4. Reverse the bits of a byte and swap its two nibbles.
  5. Write get_field and set_field to read and write a multi-bit field (position and width) inside a register value without disturbing the other bits.
  6. Isolate the lowest set bit of a word.

Hints. x & (x - 1) clears the lowest set bit. A power of two has exactly one set bit. A mask of w ones is (1u << w) - 1. Always use an unsigned constant (1u) when shifting, because shifting a signed 1 into the sign bit is undefined behavior. The lowest set bit of x is x & -x, written for unsigned values as x & (~x + 1u).

C Bit manipulation solutions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Edge cases to keep in mind: get_field with width = 32 shifts by 32, which is undefined, so handle full-width fields separately; and set_field masks the value, so a too-wide value cannot spill into neighboring fields. These are exactly the habits behind safe register access macros in vendor headers.

Part 2: memory layout, integer traps and fixed point

Problems.

  1. Detect the machine's byte order at run time. Write a function that swaps the byte order of a 32-bit word.
  2. How large is struct { uint8_t a; uint32_t b; uint8_t c; }? Why? How do you shrink it?
  3. What do these print? uint8_t a = 200, b = 100; a + b; ~m for uint8_t m = 0x0F; unsigned u = 0; u--; and int i = -1; unsigned j = 1; i < j.
  4. Multiply two Q8.8 fixed-point numbers (8 integer bits, 8 fraction bits).
  5. Add two int16_t values with saturation instead of wraparound.

Hints. Narrow types are promoted to int before arithmetic. Compilers align members to their natural size, inserting padding. In Q8.8 the real value is the integer divided by 256, so a product has 16 fraction bits and must be shifted right by 8. Saturation needs a wider intermediate.

C Layout, promotion traps, fixed point and saturation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice why saturation matters in embedded work: if a control loop's output wraps from +32767 to -32768, a motor suddenly reverses at full power. Saturating arithmetic (or an explicit clamp) turns that failure into "stay at maximum". Many DSP-style cores have saturating instructions in hardware.

Part 3: challenges to solve yourself

Write each in C and test it on the page. Aim for a solution with no floating point and no dynamic memory.

  1. Bit reversal of a 32-bit word using the swap-halves technique extended to 32 bits.
  2. Parity of a word (0 if the number of set bits is even), using x ^= x >> 16; x ^= x >> 8; ....
  3. Debounce shift register: keep an 8-bit history per button and report a press only after 0xFF, a release only after 0x00.
  4. Circular buffer with put, get, count and free_space, using free-running indexes and a power-of-two mask (see volatile and shared data).
  5. Integer square root by the bitwise method (no floating point, no library).
  6. Fast average without overflow: average of two uint32_t values without a 64-bit intermediate (hint: (a & b) + ((a ^ b) >> 1)).
  7. Run-length encode and decode a buffer, and decide what happens when the input is incompressible.
  8. Software timer wheel: support 16 one-shot timers driven by one tick, with wraparound-safe comparisons (see debouncing and software timers).
  9. CRC-16/CCITT with a 256-entry lookup table generated at startup; compare speed and memory against the bitwise version.
  10. A command-line parser for a UART console: split a line into words, look up the command in a table of function pointers, and report errors without crashing on long input.
  11. A PID controller in fixed point with output clamping and anti-windup (stop integrating when the output saturates).
  12. A state machine for a vending machine or an elevator, driven from a table, with a test that checks the invariants (see the traffic light project).

Part 4: questions to think through

These are classic design and interview questions. Write down your answer in a sentence or two before checking your notes.

  • What does volatile guarantee, and what does it not guarantee? Can a variable be both const and volatile? (Yes: a read-only hardware status register.)
  • Why must an ISR be short, and what can it safely do?
  • What is the difference between a mutex and a binary semaphore? What is priority inversion?
  • What is the stack used for, and how would you size it for a task? How do you detect overflow?
  • Why is printf a poor idea in an ISR?
  • What is the difference between static, const, and volatile for a global variable's storage and optimization?
  • What happens in the first few hundred cycles after reset, before main() runs? (Vector table, stack pointer, .data copy from flash, .bss clearing, clock setup, constructors.)
  • How would you make a firmware update safe against a power cut halfway through?
  • Why is i < n with int i and size_t n risky when i can be negative?
  • How would you measure the execution time of a function on the target, and the worst case rather than the average?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the expression (x & (x - 1)) do for a non-zero unsigned x?

    Subtracting 1 flips the lowest set bit and all bits below it; ANDing with x clears that lowest set bit.
  2. 2. In C, uint8_t a = 200, b = 100; what is the value of a + b?

    Both operands are promoted to int, so the sum is 300. Only if you store it back into a uint8_t does it wrap to 44.
  3. 3. Why does a struct with a uint8_t, a uint32_t and a uint8_t usually take 12 bytes?

    The 32-bit member is aligned on a 4-byte boundary, with padding after the first byte, and the struct is padded at the end so arrays stay aligned.
  4. 4. Which is the best way to multiply two Q8.8 numbers stored in int16_t?

    Widen to 32 bits to hold the product, then shift out the extra 8 fraction bits.
  5. 5. Why is saturating arithmetic often better than wraparound in control code?

    A wrapped control output could flip from maximum to minimum, which can be dangerous; a clamp keeps it at the limit.

Summary

  • Fluent bit manipulation (set, clear, toggle, test, fields, lowest set bit, popcount) is the base of all register-level code; use unsigned constants when shifting.
  • Narrow integers are promoted to int in expressions, signed and unsigned comparisons can surprise you, and struct layout includes padding.
  • Fixed-point and saturating arithmetic give predictable math without an FPU.
  • Practice by writing the challenges yourself and explaining the design questions out loud: that is how the skills become automatic.

You have now covered interrupts, timers, communication buses, scheduling, debugging, testing, low-power design and several projects. Keep building: pick a real board, blink an LED, read a sensor over I2C, and write a driver of your own.

Next: Back to the Embedded Systems course