Origin Academy
← Back to course

Embedded Systems Engineer Phase 0 is free

Enroll

Phase 0 · Module 2 of 5

Bits, bytes and the registers that control hardware

Number systems and bitwise logic · 12 min read

Every microcontroller is controlled by writing numbers into special memory locations called registers. Turning on an LED, starting a timer or sending a byte over a wire all come down to setting, clearing or reading individual bits in those registers. That is why embedded engineers think in binary and hexadecimal.

Binary and hex in one minute

A bit is 0 or 1. Eight bits make a byte, and a 32-bit register holds 32 of them, numbered 0 (rightmost) to 31. Hexadecimal is a shorthand where each digit stands for exactly four bits, so 0x20 is 0010 0000 in binary: only bit 5 is set. You will read hex all day in datasheets, so it pays to get fast at this conversion.

The four operations you'll use constantly

  • Set a bit: reg |= (1u << n); OR with a mask turns bit n on and leaves the rest alone.
  • Clear a bit: reg &= ~(1u << n); AND with the inverted mask turns bit n off.
  • Toggle a bit: reg ^= (1u << n); XOR flips it.
  • Read a bit: (reg >> n) & 1u shifts bit n to the bottom and masks the rest away.

Here they are in a program you can run on your laptop today. The variable stands in for a real GPIO output register; on the board in Phase 3, the same lines drive actual pins.

#include <stdint.h>
#include <stdio.h>

int main(void) {
    uint32_t reg = 0x0;           // pretend this is a GPIO output register

    reg |= (1u << 5);             // set bit 5: turn pin 5 on
    printf("after set:    0x%08X\n", reg);

    reg ^= (1u << 5);             // toggle bit 5: pin 5 off again
    printf("after toggle: 0x%08X\n", reg);

    reg |= (1u << 3) | (1u << 0); // set bits 3 and 0
    reg &= ~(1u << 3);            // clear bit 3, leave the others alone
    printf("after clear:  0x%08X\n", reg);

    int pin0_on = (reg >> 0) & 1u; // read bit 0
    printf("pin 0 is %s\n", pin0_on ? "on" : "off");
    return 0;
}
$ gcc -Wall -Wextra -std=c11 -o bits bits.c && ./bits
after set:    0x00000020
after toggle: 0x00000000
after clear:  0x00000001
pin 0 is on

Why the u in 1u matters

1 on its own is a signed int, and shifting a 1 into the sign bit (1 << 31) is undefined behavior in C. Writing 1u makes it unsigned, which is what registers are. uint32_t from stdint.h does the same job for variables: a fixed width you can rely on, whatever the compiler.

Try it

  • Change the program to set bits 0, 2 and 4 at once, then print the result in hex. What number do you get, and why?
  • Write a helper, int is_set(uint32_t reg, int n), and use it to print all 32 bits of 0xDEADBEEF.

In the full course this leads straight into C pointers and volatile, and by Phase 3 you are writing these exact operations to the real GPIO registers of an ARM Cortex-M microcontroller, without any libraries.

Next in Phase 0

The Linux command line

Continue →