Whenever I switch between CTF puzzles and network code, I end up looking up the same conversions. Say I have the four bytes de ad be ef. A debugger might show me 0xdeadbeef, a hex dump might print deadbeef, and Python might give me b'\xde\xad\xbe\xef'. What I do next depends on which representation I actually have.

A list of numbers ↔ bytes

Each number in the list represents one byte. Give the numbers to bytes() to pack them together. Give those bytes to list() to get the individual values back.

1
2
3
data = bytes([0xde, 0xad, 0xbe, 0xef])
print(data) # b'\xde\xad\xbe\xef'
print(list(data)) # [222, 173, 190, 239]

The little b in front matters in Python 3. Without it, you’re working with a text string.

Bytes ↔ printable hex

Here I want two printable hex digits for every byte. The two functions from my notes are a pair: hexlify spells the bytes out, and unhexlify reads the spelling back in.

1
2
3
4
import binascii

print(binascii.hexlify(b'\xab\xbc\xcd\xde')) # b'abbccdde'
print(binascii.unhexlify('aabbccdd')) # b'\xaa\xbb\xcc\xdd'

Bytes ↔ a single integer

To read four bytes as one number, I also have to say which end comes first. In this example de is the most significant byte, so I want big-endian order in both directions.

1
2
3
number = int.from_bytes(b'\xde\xad\xbe\xef', 'big')
print(hex(number)) # 0xdeadbeef
print(number.to_bytes(4, 'big')) # b'\xde\xad\xbe\xef'

The 4 on the way back says how many bytes to write. That detail is easy to forget when all you’ve got in front of you is an integer.