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.

6
  • 1
    you have the string in unicode? Commented Dec 3, 2015 at 17:47
  • Should there be quotes on that variable? Like s = 'Q...'? Commented Dec 3, 2015 at 17:49
  • 1
    That isn't a valid Python statement. Show some real code with expected and received results, and Python version used. Commented Dec 3, 2015 at 17:49
  • 1
    You can pull integers out of binary using the struct module. Commented Dec 3, 2015 at 17:50
  • How was the original data translated to binary? Do you have the code which performs it? It's impossible to know how to convert it back without knowing the encoding. Commented Dec 3, 2015 at 17:51

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

4 Comments

you sure it's unsigned?
@Chad, Nope, just as I am unsure if it is big- or little-endian.
OP converted hex to binary.... I assume in the same program so I'm betting on native format "@QQ".
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....
0
import struct
struct.unpack(">QQ",s)

Or

struct.unpack("<QQ",s)

Depending on the endianness of the machine that generated the bytes

1 Comment

Good answer but 5 minutes too late. This answer has already been posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.