Encoding bytes as text in Python
base64 when bytes must survive a text channel, hex when humans read it.
import base64
raw = b"typestar\x00\xff"
encoded = base64.b64encode(raw)
print(encoded, base64.b64decode(encoded) == raw)
print(base64.urlsafe_b64encode(raw))
print(raw.hex(), bytes.fromhex(raw.hex()) == raw)
print(base64.b32encode(b"ab"))
How it works
b64encodetakes and returns bytes.urlsafe_b64encodeavoids the characters a URL dislikes.bytes.hexandbytes.fromhexare the readable pair.
Keywords and builtins used here
bytesprint
The run, in numbers
- Lines
- 10
- Characters to type
- 241
- Tokens
- 73
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 40 seconds.
Step 2 of 2 in Bytes & secrets, step 31 of 41 in Domain tools.