How to pack a UUID into a struct in Python?
It is a 128-bit integer, what would you expect it to be turned into? You can split it into several components — e.g. two 64-bit integers:
max_int64 = 0xFFFFFFFFFFFFFFFF
packed = struct.pack('>QQ', (u.int >> 64) & max_int64, u.int & max_int64)
# unpack
a, b = struct.unpack('>QQ', packed)
unpacked = (a << 64) | b
assert u.int == unpacked
As you're using uuid
module, you can simply use bytes
member, which holds UUID as a 16-byte string (containing the six integer fields in big-endian byte order):
u = uuid.uuid4()
packed = u.bytes # packed is a string of size 16
assert u == uuid.UUID(bytes=packed)