Reputation: 5848
I have a string of binary I'm trying to convert to ints. The chunks were originally 8 hex chars each and converted into binary. How do you turn it into its 64-bit int value?
s = 'Q\xcb\x80\x80\x00\x00\x01\x9bQ\xcc\xd2\x00\x00\x00\x01\x9b'
date_chunk = s[0:8]
value_chunk = s[8:]
Looks like hex now that I got it to print. How do I make two ints? The first is a date encoded to seconds since epoch.
Upvotes: 0
Views: 405
Reputation: 177600
The struct
module unpacks binary. Use qq
for signed ints.
>>> s = 'Q\xcb\x80\x80\x00\x00\x01\x9bQ\xcc\xd2\x00\x00\x00\x01\x9b'
>>> len(s)
16
>>> import struct
>>> struct.unpack('>QQ',s) # big-endian
(5893945824588595611L, 5894316909762970011L)
>>> struct.unpack('<QQ',s) # little-endian
(11169208553011465041L, 11169208550869355601L)
You also mentioned an original 8 hex chars. Use the binascii.unhexlify
function in that case. Example:
>>> s = '11223344'
>>> import binascii
>>> binascii.unhexlify(s)
'\x11"3D'
>>> struct.unpack('>L',binascii.unhexlify(s))
(287454020,)
>>> hex(287454020)
'0x11223344'
Upvotes: 4
Reputation: 337
import struct
struct.unpack(">QQ",s)
Or
struct.unpack("<QQ",s)
Depending on the endianness of the machine that generated the bytes
Upvotes: 0