0

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
  • 16,415
  • 8
  • 44
  • 58
Justin Thomas
  • 5,680
  • 3
  • 38
  • 63

2 Answers2

4

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'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0
import struct
struct.unpack(">QQ",s)

Or

struct.unpack("<QQ",s)

Depending on the endianness of the machine that generated the bytes

Jas
  • 327
  • 2
  • 9