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.
Siyual
17k8 gold badges47 silver badges60 bronze badges
asked Dec 3, 2015 at 17:44
Justin Thomas
5,8473 gold badges44 silver badges63 bronze badges
2 Answers 2
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'
answered Dec 3, 2015 at 17:53
Mark Tolonen
181k26 gold badges184 silver badges279 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Chad S.
you sure it's unsigned?
Mark Tolonen
@Chad, Nope, just as I am unsure if it is big- or little-endian.
tdelaney
OP converted hex to binary.... I assume in the same program so I'm betting on native format
"@QQ".Mark Tolonen
Both numbers seem quite large for seconds since an epoch, but if the OP wants to tell us what the expected date should be and what epoch it is based....
import struct
struct.unpack(">QQ",s)
Or
struct.unpack("<QQ",s)
Depending on the endianness of the machine that generated the bytes
1 Comment
tdelaney
Good answer but 5 minutes too late. This answer has already been posted.
lang-py
s = 'Q...'?structmodule.