Binary Files · 4 / 14 Theory

Showing bytes in hexadecimal and common mistakes

To inspect a binary file a hexadecimal viewer is used: it shows the bytes in hexadecimal and, next to them, those that correspond to printable characters. Building one sums up almost everything seen in the lesson.

Formatting hexadecimal numbers

n = 255
print(f"{n:x}")      # ff
print(f"{n:02x}")    # ff       (2 digits, leading zeros)
print(f"{10:02x}")   # 0a
print(f"{10:02X}")   # 0A       (capitals)
print(f"{4096:08x}")  # 00001000 (8 digits)

Going through a file 16 at a time

range with a step lets you advance by blocks of 16 bytes:

data = b"Hello world, this is an example"
for position in range(0, len(data), 16):
    block = data[position:position + 16]   # the last one may be shorter
    print(position, block)

The bytes of a block in hexadecimal

block = b"Hello world"
hex_part = " ".join(f"{byte:02x}" for byte in block)
print(hex_part)    # 48 65 6c 6c 6f 20 77 6f 72 6c 64

When going through a bytes, each byte is already an integer, ready to format.

The characters column

Only bytes between 32 and 126 are printable ASCII characters. The rest is replaced by a dot:

chars = "".join(chr(b) if 32 <= b <= 126 else "." for b in block)
print(chars)   # Hello world

Aligning columns

So that the last row (which may have fewer bytes) lines up with the others, it is padded with spaces to a fixed width using :<N. A block of 16 bytes in hexadecimal takes 16 × 2 + 15 = 47 characters:

print(f"{0:08x}  {hex_part:<47}  |{chars}|")
# 00000000  48 65 6c 6c 6f 20 77 6f 72 6c 64                 |Hello world|

With this you have all the pieces of Hexadecimal viewer: the offset in {position:08x}, the aligned hexadecimal part, and the characters between bars. The exact format of the statement (spaces, bars, paging) must be respected to the character.

Common mistakes with binary files

  • Opening a binary file in text mode: UnicodeDecodeError appears or line breaks are altered. Always use "rb", "wb".
  • Mixing str and bytes: b"BM" == "BM" is False; f.write("abc") in binary mode raises TypeError; b"a" + "b" too.
  • Confusing a byte with a character: data[0] is an integer. To get a bytes of length 1 use data[0:1].
  • Forgetting seek(0) before writing after having read in r+b.
  • Using "wb" on the original: it deletes the file. Write to a different file.
  • Loading a huge file with read(): use blocks.
  • Forgetting the last block: when splitting or copying, the last one is usually shorter; do not discard it.
  • Wrong byte order in multi-byte numbers: check whether it is little or big-endian.
data = b"ABC"
print(data[0])      # 65   (an integer)
print(data[0:1])    # b'A' (a bytes)
print(data[0] == "A")        # False: integer versus text
print(data[0:1] == b"A")     # True