Lesson 2 of 9
Hexadecimal notation
- 12 min
- 5 checks
- 3 hints
- Go to task
Goal
A byte is two hex digits
Explanation
The hexadecimal system writes numbers with sixteen symbols: the digits 0 to 9, then the letters a to f. In Python a hex number starts with the prefix 0x, so 0xff is 255. Because each hex digit stands for exactly four bits, a byte is always written as two digits, from 00 to ff, and that's why reverse engineers read bytes this way.
Python has ready-made tools for converting. The data.hex(" ") method shows the bytes with a space between them, bytes.fromhex("ff 00") does the reverse and ignores the spaces, and format(26, "02x") writes a single number as two digits, giving "1a". A number made of several bytes is read with int.from_bytes.
The place you'll see this most is a hexdump. Each line shows the starting address, then sixteen bytes, then the same bytes as text between two vertical bars, with a dot standing in for every byte that can't be printed:
00000000 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR|
Your task
Write a function to_hex(data) that returns the bytes as a hex string with a space between bytes, like "ff 00 1a", and a function from_hex(text) that reverses it and returns bytes. Then set value to the integer you get by reading the two bytes bytes([0x12, 0x34]) with int.from_bytes in "big" byte order. You'll see what that order means in the next lesson.
Checks
5 checks- to_hex separates the bytes with a space
- to_hex writes a small byte as two digits
- from_hex reverses to_hex
- from_hex ignores spaces and returns bytes
- value holds the right number