Examples-Hex to Binary Conversion Examples With STM32F407 Registers and C Code-Free Embedded C Course Online

Need Help or More Information?

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

MODULE 2 · LESSON 2.2 · WORKED EXAMPLES

Hex to Binary Conversion Examples With STM32F407 Registers and C Code

Twelve worked examples: nibble diagrams, padding, hex arithmetic, register address breakdown, RGB565 packing, a hex dump tool, a hex parser and the sign-extension trap, with compiled and verified C programs.

12
Examples
7 C programs
Compiled & run
Beginner
Level

Hex to Binary Conversion Examples and More: What This Page Covers

Theory gives you the rules; this page gives you the reps. These hex to binary conversion examples start with single bytes, grow to 32-bit values and real STM32F407 register addresses, and end with working C programs: a hex dump utility, an RGB565 colour packer and a hex-string parser. Every C program was compiled with GCC and run; the green boxes show real output.

#ExampleSkill
1Hex to binary with nibble diagrams4-bit expansion
2Binary to hex, including paddingGrouping from the right
3Hex to decimal with place-value diagramsWeights of 16
4Decimal to hex by repeated divisionDivision by 16
5Register address breakdown: 0x40020C00Base + offset, bus regions
6Hex arithmetic: carries and borrowsOffsets, region sizes
7Byte, nibble, half-word and word diagramsSplitting and combining
8RGB565 colours in hex (display drivers)Packing fields
9A hex dump utility in CDebug tooling
10Parsing hex text without a libraryChar to nibble
11Sign-extension trap when printing bytesPitfall and fix
12Mini exercises with hidden answersSelf-test
Method: Do each conversion on paper before you read the solution. Speed comes from the 16 nibble patterns: after a week of practice, 0xB5 → 1011 0101 takes no time at all.

Example 1: Hex to Binary With Nibble Diagrams

Rule: every hex digit becomes exactly four bits. Never skip the leading zeros of a nibble: 0x2 is 0010, not 10.

1a. A single byte: 0x2F

0x2F = 0010 1111
2
▼
0
0
1
0
= 2
F
▼
1
1
1
1
= 15

2 = 0010 and F = 1111, so 0x2F = 0010 1111 = 47 decimal (32 + 15).

1b. A half-word: 0xA5C3

0xA5C3 = 1010 0101 1100 0011
A
▼
1
0
1
0
= 10
5
▼
0
1
0
1
= 5
C
▼
1
1
0
0
= 12
3
▼
0
0
1
1
= 3

The upper byte 0xA5 is 1010 0101, the lower byte 0xC3 is 1100 0011. Notice that byte boundaries fall exactly between hex digit pairs: a big advantage of hex.

1c. A full 32-bit word: 0xDEADBEEF

0xDEADBEEF — eight digits, thirty-two bits
D
▼
1
1
0
1
= 13
E
▼
1
1
1
0
= 14
A
▼
1
0
1
0
= 10
D
▼
1
1
0
1
= 13
B
▼
1
0
1
1
= 11
E
▼
1
1
1
0
= 14
E
▼
1
1
1
0
= 14
F
▼
1
1
1
1
= 15

This famous “magic number” is used by debug allocators and fill patterns because it reads as a word and is easy to spot in a memory dump.

Example 2: Binary to Hex, Including Padding

Rule: group from the right, pad the left group with zeros, then replace each group.

2a. Exact multiple of four bits: 1101 0110

11010110 → D 6
1101 0110
8 bits
➜
1101 | 0110
two groups
➜
D | 6
13 | 6
➜
0xD6
result = 214

2b. Twelve bits: 1011 0011 1110

101100111110 → B 3 E
101100111110
12 bits
➜
1011 | 0011 | 1110
three groups
➜
B | 3 | E
11 | 3 | 14
➜
0xB3E
result = 2878

2c. Odd length (needs padding): 1 0110 1111 (9 bits)

9 bits → pad one zero on the LEFT → 0001 0110 1111 = 0x16F
101101111
9 bits
➜
Group from right
1 | 0110 | 1111
➜
Pad left group
0001 | 0110 | 1111
➜
Replace
1 | 6 | F
➜
0x16F
result = 367
BinaryGrouped (from the right)HexDecimal
101010100xA10
1010100010 10100x2A42
11111110111 11110x7F127
1000000000001 0000 00000x100256
111111111110111 1111 11110x7FF2047
Pattern to recognise: A run of ones is always F or 7, 3, 1 on the leftmost digit: 7 bits → 0x7F, 11 bits → 0x7FF, 16 bits → 0xFFFF. A single 1 followed by zeros is 1, 2, 4 or 8 followed by that many zeros: 0x80, 0x400, 0x8000.

Example 3: Hex to Decimal With Place-Value Diagrams

Multiply each digit by its weight (1, 16, 256, 4096 …) and add.

0x7F = 7×16 + 15 = 127
weight
digit
digit × weight
161
16
7
112
160
1
F
15
7 × 16 + 15 × 1 = 127
0x1234 = 4660
weight
digit
digit × weight
163
4,096
1
4096
162
256
2
512
161
16
3
48
160
1
4
4
1 × 4096 + 2 × 256 + 3 × 16 + 4 × 1 = 4660
0xABCD = 43981
weight
digit
digit × weight
163
4,096
A
40960
162
256
B
2816
161
16
C
192
160
1
D
13
10 × 4096 + 11 × 256 + 12 × 16 + 13 × 1 = 43981
HexDecimalWhy it matters
0x7F127Largest signed 8-bit value (Lesson 2.3)
0x80128Bit 7 only
0xFF255Largest byte
0x3FF1023Largest 10-bit value
0xFFF4095Largest 12-bit ADC value
0xFFFF65535Largest 16-bit value
0x7FFFFFFF2147483647Largest signed 32-bit value
Shortcut: Memorise the “all ones” values: they are one less than a power of two. 0xFFF = 4096 − 1.

Example 4: Decimal to Hex by Repeated Division by 16

Convert 4660 to hexadecimal. Divide by 16 repeatedly; remainders 10–15 become A–F; read bottom to top.

Division table for 4660 (base 16)
StepDivideQuotientRemainder
14660 ÷ 162914
2291 ÷ 16183
318 ÷ 1612
41 ÷ 1601
▲ Read the remainders from the last step up to the first step (bottom to top)

Remainders from bottom to top: 1, 2, 3, 4, so 4660 = 0x1234. This matches the weights diagram in Example 3, which is the best self-check available.

Shortcut through binary for values below 256

For 200: weights give 1100 1000; regroup as C and 8: 0xC8. Quick check: 12 × 16 + 8 = 200.

DecimalHexDecimalHex
100xA1000x64
150xF2000xC8
160x102550xFF
320x202560x100
640x4010000x3E8
1280x8010240x400

Example 5: Breaking Down a Register Address (0x40020C00)

How does the CPU “find” GPIOD? Through its address. Read 0x40020C00 from the left:

0x40020C00 decoded digit by digit
4
peripheral
0
region
0
bus
2
AHB1
0
block
C
port D
0
offset
0
MODER
DigitsMeaningCalculation
0x4000 0000Start of the peripheral region (APB1 begins here)Fixed by the memory map
+ 0x0002 0000AHB1 bus is 0x20000 above PERIPH_BASE0x40000000 + 0x20000 = 0x40020000
+ 0x0000 0C00GPIOD block: ports are 0x400 apart; D is the 4th (A,B,C,D)3 × 0x400 = 0xC00
+ 0x14Offset of ODR inside the port0x40020C00 + 0x14 = 0x40020C14
addr_calc.c — the CMSIS-style macro chain
#include <stdio.h> #include <stdint.h> #define PERIPH_BASE 0x40000000UL #define AHB1_BASE (PERIPH_BASE + 0x00020000UL) #define GPIOD_BASE (AHB1_BASE + 0x0C00UL) #define GPIOD_MODER (GPIOD_BASE + 0x00UL) #define GPIOD_IDR (GPIOD_BASE + 0x10UL) #define GPIOD_ODR (GPIOD_BASE + 0x14UL) #define GPIOD_BSRR (GPIOD_BASE + 0x18UL) int main(void) { printf(“PERIPH_BASE = 0x%08lX\n”, PERIPH_BASE); printf(“AHB1_BASE = 0x%08lX\n”, AHB1_BASE); printf(“GPIOD_BASE = 0x%08lX\n”, GPIOD_BASE); printf(“GPIOD_MODER = 0x%08lX\n”, GPIOD_MODER); printf(“GPIOD_IDR = 0x%08lX\n”, GPIOD_IDR); printf(“GPIOD_ODR = 0x%08lX\n”, GPIOD_ODR); printf(“GPIOD_BSRR = 0x%08lX\n”, GPIOD_BSRR); printf(“distance ODR – MODER = %lu bytes\n”, GPIOD_ODR – GPIOD_MODER); return 0; }
Output (verified)
PERIPH_BASE = 0x40000000 AHB1_BASE = 0x40020000 GPIOD_BASE = 0x40020C00 GPIOD_MODER = 0x40020C00 GPIOD_IDR = 0x40020C10 GPIOD_ODR = 0x40020C14 GPIOD_BSRR = 0x40020C18 distance ODR – MODER = 20 bytes
gpio_pointer.c — how the CMSIS header turns an address into a register (target code)
/* An address becomes a register when we cast it to a volatile pointer */ #define GPIOD_ODR_REG (*(volatile uint32_t *)0x40020C14UL) GPIOD_ODR_REG = 0x00001000UL; /* write: PD12 high, everything else low */ uint32_t pins = GPIOD_ODR_REG; /* read the register back */
Why volatile? The compiler must not cache or remove accesses to a hardware register. Module 14 explains volatile in detail; for now remember: address + cast to volatile pointer = register.

Example 6: Hex Arithmetic — Carries, Borrows and Region Sizes

Addition carries when a column reaches 16, subtraction borrows 16. Work through these:

0xFF + 0x01 = 0x100 (the carry ripples through both digits)
carry
1
1
A
F
F
+ B
0
1
sum
1
0
0
0x7A3 + 0x0DE = 0x881
carry
1
1
A
7
A
3
+ B
0
D
E
sum
8
8
1

Subtraction with borrow: 0x1000 − 0x1

The rightmost digit 0 − 1 borrows 16 from the left. The zeros ripple the borrow all the way until the leading 1 gives it: 0x1000 − 1 = 0xFFF. This is why the top address of a 4 KB block starting at 0 is 0xFFF.

hex_arith.c
#include <stdio.h> #include <stdint.h> int main(void) { printf(“0x2F + 0x1B = 0x%X\n”, 0x2F + 0x1B); printf(“0xFF + 0x01 = 0x%X\n”, 0xFF + 0x01); printf(“0x1000 – 0x1 = 0x%X\n”, 0x1000 – 0x1); printf(“0xC8 – 0x5A = 0x%X\n”, 0xC8 – 0x5A); printf(“Flash end = 0x%08lX\n”, 0x08000000UL + 0x100000UL – 1UL); printf(“SRAM end = 0x%08lX\n”, 0x20000000UL + 0x20000UL); printf(“Region size = %lu bytes\n”, 0x2001C000UL – 0x20000000UL); return 0; }
Output (verified)
0x2F + 0x1B = 0x4A 0xFF + 0x01 = 0x100 0x1000 – 0x1 = 0xFFF 0xC8 – 0x5A = 0x6E Flash end = 0x080FFFFF SRAM end = 0x20020000 Region size = 114688 bytes
ProblemWorkingAnswer
0x80 + 0x7F128 + 127 = 2550xFF
0x100 − 0x1256 − 10xFF
0xAAAA + 0x555643690 + 21846 = 655360x10000 (carry out of 16 bits)
0x20000000 + 0x4000add to second digit group0x20004000
0x08004000 − 0x08000000end − start0x4000 = 16 KB sector size

Example 7: Byte, Nibble, Half-word and Word Diagrams

A 32-bit word can be seen at four levels. Hex shows every level at once, because each level is a whole number of digits.

0xCAFEBABE seen as nibbles, bytes and half-words
C
nibble 7
A
nibble 6
F
nibble 5
E
nibble 4
B
nibble 3
A
nibble 2
B
nibble 1
E
nibble 0
CA
byte 3
FE
byte 2
BA
byte 1
BE
byte 0
CAFE
upper half-word
BABE
lower half-word
split_word.c — splitting and rebuilding
#include <stdio.h> #include <stdint.h> int main(void) { uint32_t w = 0xCAFEBABEu; uint8_t b3 = (uint8_t)(w >> 24); uint8_t b2 = (uint8_t)(w >> 16); uint8_t b1 = (uint8_t)(w >> 8); uint8_t b0 = (uint8_t)(w); uint16_t hi = (uint16_t)(w >> 16); uint16_t lo = (uint16_t)(w & 0xFFFFu); printf(“bytes : %02X %02X %02X %02X\n”, b3, b2, b1, b0); printf(“half-words: %04X %04X\n”, hi, lo); /* rebuild a word from four bytes received (MSB first) */ uint8_t rx[4] = { 0xDE, 0xAD, 0xBE, 0xEF }; uint32_t r = ((uint32_t)rx[0] << 24) | ((uint32_t)rx[1] << 16) | ((uint32_t)rx[2] << 8) | rx[3]; printf(“rebuilt : 0x%08X\n”, (unsigned)r); return 0; }
Output (verified)
bytes : CA FE BA BE half-words: CAFE BABE rebuilt : 0xDEADBEEF
Pattern: To extract: (w >> shift) & mask. To build: cast each part to the wide type, << it into place and OR them together. The shift amounts are always multiples of 4 (nibble) or 8 (byte), which is why hex reads so naturally.

Example 8: RGB565 Colours in Hex (LCD Display Drivers)

Small TFT displays (ILI9341, ST7735) take colours as 16-bit RGB565 values: 5 bits red, 6 bits green, 5 bits blue. Hex shows the fields: white is 0xFFFF, pure red 0xF800, pure green 0x07E0 and pure blue 0x001F.

RGB565 layout of a 16-bit pixel (orange 0xFD20)
15
1
14
1
13
1
12
1
11
1
10
1
9
0
8
1
7
0
6
0
5
1
4
0
3
0
2
0
1
0
0
0
Red: bits 15..11Green: bits 10..5Blue: bits 4..0
rgb565.c
#include <stdio.h> #include <stdint.h> /* Pack 8-bit R, G, B into RGB565: RRRRR GGGGGG BBBBB */ uint16_t rgb565(uint8_t r, uint8_t g, uint8_t b) { return (uint16_t)(((r & 0xF8u) << 8) | ((g & 0xFCu) << 3) | (b >> 3)); } int main(void) { printf(“white (255,255,255) -> 0x%04X\n”, rgb565(255, 255, 255)); printf(“red (255, 0, 0) -> 0x%04X\n”, rgb565(255, 0, 0)); printf(“green ( 0,255, 0) -> 0x%04X\n”, rgb565(0, 255, 0)); printf(“blue ( 0, 0,255) -> 0x%04X\n”, rgb565(0, 0, 255)); printf(“orange (255,165, 0) -> 0x%04X\n”, rgb565(255, 165, 0)); return 0; }
Output (verified)
white (255,255,255) -> 0xFFFF red (255, 0, 0) -> 0xF800 green ( 0,255, 0) -> 0x07E0 blue ( 0, 0,255) -> 0x001F orange (255,165, 0) -> 0xFD20

How the packing works

  • r & 0xF8 keeps the top 5 bits of red (0xF8 = 1111 1000); << 8 moves them to bits 15..11.
  • g & 0xFC keeps the top 6 bits of green (0xFC = 1111 1100); << 3 puts them at bits 10..5.
  • b >> 3 keeps the top 5 bits of blue and moves them to bits 4..0.
  • The three parts never overlap, so OR combines them.

Example 9: A Hex Dump Utility in C

Debugging firmware often means looking at raw buffers: a received UART frame, a flash page, an I2C transaction. A hex dump prints the address, the bytes in hex and the printable characters, exactly as the xxd command or the CubeIDE memory view does.

hexdump.c — 16 bytes per line with an ASCII column
#include <stdio.h> #include <stdint.h> #include <stddef.h> void hexdump(const void *data, size_t len, uint32_t base) { const uint8_t *p = (const uint8_t *)data; for (size_t i = 0; i < len; i += 16) { printf(“%08X “, (unsigned)(base + i)); for (size_t j = 0; j < 16; j++) { if (i + j < len) printf(“%02X “, p[i + j]); else printf(” “); if (j == 7) printf(” “); } printf(” |”); for (size_t j = 0; j < 16 && (i + j) < len; j++) { uint8_t c = p[i + j]; putchar((c >= 32U && c < 127U) ? (int)c : ‘.’); } printf(“|\n”); } } int main(void) { const uint8_t buf[] = { ‘S’,‘T’,‘M’,‘3’,‘2’,‘F’,‘4’,‘0’,‘7’, 0x0A, 0xFF, 0x00, 0x7F, 0x80, ‘E’,‘n’,‘d’,‘!’, 0xDE, 0xAD, 0xBE, 0xEF }; hexdump(buf, sizeof(buf), 0x20000000u); return 0; }
Output (verified)
20000000 53 54 4D 33 32 46 34 30 37 0A FF 00 7F 80 45 6E |STM32F407…..En| 20000010 64 21 DE AD BE EF |d!….|

What to notice

  • %08X prints the address with eight hex digits, zero padded, so columns line up.
  • %02X prints every byte as exactly two digits; without the zero, 0x0A would print as A and break the layout.
  • Bytes outside 32–126 are not printable, so they are shown as a dot.
  • The extra space after the 8th byte makes the long row easier to scan.
  • On a target you would replace printf with your UART print function.

Example 10: Parsing Hex Text Without a Library Function

A command-line interface on a UART (“write 0x40020C14 0x1000”) must parse hex typed by a human. The key trick: shift left by 4 and OR in the new digit, the hex counterpart of the doubling method from Lesson 2.1.

parse_hex.c
#include <stdio.h> #include <stdint.h> int hex_val(char c) { if (c >= ‘0’ && c <= ‘9’) return c – ‘0’; if (c >= ‘A’ && c <= ‘F’) return c – ‘A’ + 10; if (c >= ‘a’ && c <= ‘f’) return c – ‘a’ + 10; return –1; /* not a hex digit */ } /* Parse up to 8 hex digits; returns 1 on success */ int parse_hex(const char *s, uint32_t *out) { uint32_t v = 0; int n = 0; if (s[0] == ‘0’ && (s[1] == ‘x’ || s[1] == ‘X’)) s += 2; /* skip prefix */ for (; *s != ‘\0’; s++, n++) { int d = hex_val(*s); if (d < 0 || n >= 8) return 0; v = (v << 4) | (uint32_t)d; /* shift one nibble, add digit */ } *out = v; return n > 0; } /* Value 0..15 to character using a lookup table */ char nibble_to_char(uint8_t n) { return “0123456789ABCDEF”[n & 0xFu]; } int main(void) { const char *tests[] = { “3E8”, “0x40020C14”, “ff”, “DEADBEEF”, “12G4”, “” }; for (unsigned i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) { uint32_t v; if (parse_hex(tests[i], &v)) printf(“\”%s\” -> %u (0x%X)\n”, tests[i], (unsigned)v, (unsigned)v); else printf(“\”%s\” -> invalid\n”, tests[i]); } printf(“nibble_to_char: %c %c %c\n”, nibble_to_char(0), nibble_to_char(10), nibble_to_char(15)); return 0; }
Output (verified)
“3E8” -> 1000 (0x3E8) “0x40020C14” -> 1073875988 (0x40020C14) “ff” -> 255 (0xFF) “DEADBEEF” -> 3735928559 (0xDEADBEEF) “12G4” -> invalid “” -> invalid nibble_to_char: 0 A F

Design notes

  • hex_val accepts both cases: c - 'A' + 10 maps A to 10, F to 15.
  • The n >= 8 guard prevents overflow of a 32-bit result.
  • Invalid input returns 0 instead of a guessed value: never silently accept garbage in a debug console.
  • nibble_to_char uses a 16-character string as a lookup table; masking with 0xF keeps the index in range.

Example 11: The Sign-Extension Trap When Printing Bytes in Hex

A very common bug in hex dump code: the byte is stored in a signed variable (char is signed on many platforms). When a value with bit 7 set is passed to printf, it is promoted to int with sign extension, so 0xFF becomes 0xFFFFFFFF and the output has eight digits instead of two.

signext.c
#include <stdio.h> #include <stdint.h> int main(void) { int8_t sb = (int8_t)0xFF; /* signed byte holding the bit pattern FF */ uint8_t ub = 0xFF; printf(“WRONG : %02X\n”, (unsigned)sb); /* sign-extended to 32 bits */ printf(“RIGHT : %02X\n”, (unsigned)(uint8_t)sb); /* keep only 8 bits */ printf(“OK : %02X\n”, (unsigned)ub); /* unsigned: no problem */ printf(“mask : %02X\n”, (unsigned)sb & 0xFFu); /* masking also works */ return 0; }
Output (verified)
WRONG : FFFFFFFF RIGHT : FF OK : FF mask : FF
Why 0xFF turns into 0xFFFFFFFF: promotion copies the sign bit upward
int8_t
1
1
1
1
1
1
1
1
▼ promote to 32-bit int (copy bit 7 into 24 new bits)
int
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
Rule: Store raw bytes in uint8_t, never in plain char or int8_t, whenever you print, shift or compare them as bit patterns. Lesson 2.3 explains why bit 7 gets copied.

Example 12: Mini Exercises — Try It Yourself

Exercise 1. Convert 0xB5 to binary and decimal.
1011 0101 = 181
Exercise 2. Convert 0x7E3 to binary.
0111 1110 0011
Exercise 3. Convert 1110 0010 1010 to hex.
0xE2A
Exercise 4. Convert decimal 300 to hex.
0x12C (1×256 + 2×16 + 12)
Exercise 5. What is 0x3F + 0x01?
0x40 (F + 1 = 16 → write 0, carry 1)
Exercise 6. GPIOB base is 0x40020400. What is the address of GPIOB_ODR (offset 0x14)?
0x40020414
Exercise 7. What is the last address of a 16 KB region starting at 0x08000000?
0x08003FFF (16 KB = 0x4000; subtract 1)
Exercise 8. Write the mask that clears bits 11:8 of a 16-bit register.
~0x0F00 (then AND with 0xFFFF): 0xF0FF
Exercise 9. RGB565 for pure red + pure green mixed (255,255,0)?
0xFFE0 (0xF800 | 0x07E0)
function revealAns(btn){var d=btn.nextElementSibling,o=d.style.display===’block’;d.style.display=o?’none’:’block’;btn.textContent=o?’Show answer’:’Hide answer’;}

Quick Reference Card

TaskRecipe
Hex → binaryEach digit → 4 bits (8-4-2-1)
Binary → hexGroup from the right in fours, pad left, replace
Hex → decimalSum of digit × 16position
Decimal → hexDivide by 16, remainders bottom to top
Address of a registerBase + offset
Extract a byte(w >> 8*n) & 0xFF
Print a registerprintf("0x%08X", (unsigned)reg)
Print a byteprintf("%02X", (uint8_t)b)

Examples done?

Lock in the skill with the quiz: hex conversions, address-to-peripheral matching, code snippet challenges and interview questions with full answers.

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 *