Lesson 3 of 9

Byte order

Goal

The same number stored two ways in memory

01

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").

02

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
  1. read_u32 reads little-endian
  2. read_u32 reads big-endian when asked
  3. read_u32 reads the first four bytes of any data
  4. both returns the two readings in order
  5. Only four bytes are read, even from longer data
03

Hints

0/3
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.