Project 5: Endianness Inspector and Byte Swapper
- File: P05-endianness-inspector.md
- Main Programming Language: C
- Alternative Programming Languages: Rust, Go, Python
- Coolness Level: Level 3 (See REFERENCE.md)
- Business Potential: Level 1 (See REFERENCE.md)
- Difficulty: Level 2 (See REFERENCE.md)
- Knowledge Area: Endianness
- Software or Tool: CLI
- Main Book: “Computer Systems: A Programmer’s Perspective”
What you will build: A tool that detects host endianness and swaps byte order for 16-, 32-, and 64-bit values.
Why it teaches binary/hex: Endianness is the difference between byte order and value meaning.
Core challenges you will face:
- Byte-order detection -> Endianness
- Swap correctness -> Endianness
- Formatting -> Bits/Bytes/Nibbles
Real World Outcome
$ endian-check
host_order: little-endian
$ endian-swap --width 32 --value 0x12345678
swapped: 0x78563412
The Core Question You Are Answering
“When do the same bytes mean a different number?”
Concepts You Must Understand First
- Network byte order
- Why is it big-endian?
- Book Reference: “Computer Systems: A Programmer’s Perspective” - Ch. 2
- Byte swapping
- How do you reverse byte order without losing bits?
- Book Reference: “Computer Systems: A Programmer’s Perspective” - Ch. 2
Questions to Guide Your Design
- Detection
- How will you detect host order at runtime?
- Swapping
- Will you implement swaps with shifts and masks or byte arrays?
Thinking Exercise
Byte Order Table
Write the bytes of 0x01020304 in both endian orders.
Questions to answer:
- Which order matches memory on your machine?
- Which order matches network order?
The Interview Questions They Will Ask
- “What is network byte order?”
- “How do you detect endianness at runtime?”
- “Why do file formats specify byte order?”
- “How do you swap bytes without using library functions?”
- “What breaks if you ignore endianness?”
Hints in Layers
Hint 1: Starting Point Use a 16-bit value 0x0102 and inspect its byte order in memory.
Hint 2: Next Level Implement swap by shifting bytes into new positions.
Hint 3: Technical Details Pseudocode:
swap32(x):
return (x>>24) | ((x>>8)&0xFF00) | ((x<<8)&0xFF0000) | (x<<24)
Hint 4: Tools/Debugging
Compare against htonl and ntohl results.
Books That Will Help
| Topic | Book | Chapter |
|---|---|---|
| Byte order | “Computer Systems: A Programmer’s Perspective” | Ch. 2 |
Common Pitfalls and Debugging
Problem 1: “Swap works for 16-bit but not 32-bit”
- Why: You are not masking intermediate shifts.
- Fix: Mask each shifted byte before recombining.
- Quick test: Swap 0x01020304 -> 0x04030201.
Definition of Done
- Detects host endianness
- Swaps 16/32/64-bit values correctly
- Includes test vectors
- Explains when to use network byte order