Lesson 2 of 9

Hexadecimal notation

Goal

A byte is two hex digits

01

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|
02

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
  1. to_hex separates the bytes with a space
  2. to_hex writes a small byte as two digits
  3. from_hex reverses to_hex
  4. from_hex ignores spaces and returns bytes
  5. value holds the right number
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”.