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 | data = bytes([0xde, 0xad, 0xbe, 0xef]) |
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 | import binascii |
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 | number = int.from_bytes(b'\xde\xad\xbe\xef', 'big') |
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.