Lesson 3 of 9
Byte order
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
The same number stored two ways in memory
Explanation
A single byte can't hold every number: 0x12345678 needs four bytes. That raises an important question: in what order are those bytes stored in memory? This is called endianness, and there are two ways to do it:
(0x12345678).to_bytes(4, "big") 12 34 56 78 (0x12345678).to_bytes(4, "little") 78 56 34 12
Big-endian puts the most significant byte first, the way we write numbers, and little-endian puts the least significant byte first. Both x86 and most ARM processors are little-endian, so if you read a number in the wrong order you get a meaningless value. The bytes 01 00 00 00 are 1 in little-endian and 16777216 in big-endian.
In Python you read a number with int.from_bytes(b, "little") or int.from_bytes(b, "big"), and write one with n.to_bytes(4, "little").
Your task
Write a function read_u32(data, little=True) that reads the first four bytes of data as an unsigned integer in little-endian order, or in big-endian order if little is False. Then write a function both(data) that returns a tuple with both readings, little-endian first and big-endian second.
Checks
5 checks- read_u32 reads little-endian
- read_u32 reads big-endian when asked
- read_u32 reads the first four bytes of any data
- both returns the two readings in order
- Only four bytes are read, even from longer data