1

I want to convert a 64 bit integer to a byte array of length 16.

For example, I want to convert 687198803487 to [31 150 61 0 160 0 0 0 0 0 0 0 0 0 0 0]

In Go, I'm able to do this using

id := make([]byte, 16)
binary.LittleEndian.PutUint64(id, uint64(687198803487))

How can I replicate this in Python 2?

3
  • Have a look at the struct module. Format d deals with type double. Commented Jul 10, 2018 at 1:47
  • 1
    struct.unpack('8B', struct.pack('>Q', x))[::-1] Commented Jul 10, 2018 at 1:48
  • This is not a duplicate as the other question does not start from a uint64 or something similar Commented Sep 8, 2022 at 18:05

1 Answer 1

1

Use struct.pack with '<Q' to do this. Here < indicates little-Endian, and Q means we want to pack an unsigned long long (8 bytes). If you want to convert it to 16 bytes, however, you have to fill zeros on your own (your input is only 64 bits after all).

>>> import struct
>>> struct.pack('<Q', 687198803487)
b'\x1f\x96=\x00\xa0\x00\x00\x00'
>>> list(map(int, struct.pack('<Q', 687198803487)))
[31, 150, 61, 0, 160, 0, 0, 0]
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

Please flag these questions as duplicates instead of answering them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.