-2

I have a list of big numbers:

[123456, 654321]

And I am converting every number to bytes:

lst = [(123456).to_bytes(6,'big'), (654321).to_bytes(6,'big')]
>>> [b'\x00\x00\x00\x01\xe2@', b'\x00\x00\x00\t\xfb\xf1']

And then I am converting this list into bytes:

by = b''.join(lst)
>>> b'\x00\x00\x00\x01\xe2@\x00\x00\x00\t\xfb\xf1'

How can I convert back from b'\x00\x00\x00\x01\xe2@\x00\x00\x00\t\xfb\xf1' to [123456, 654321]?

Kevin
  • 1,103
  • 10
  • 33
  • 1
    This might also be useful: [How do you split a list into evenly sized chunks?](/q/312443/4518341) It says "list", but it works on any [sequence](https://docs.python.org/3/glossary.html#term-sequence), including `bytes`. – wjandrea Nov 13 '21 at 20:41

1 Answers1

2

You can use slicing on byte objects:

>>> value = b'\x00\x00\x00\x01\xe2@\x00\x00\x00\t\xfb\xf1'

>>> byte1 = value[:6]
>>> print(byte1)
b'\x00\x00\x00\x01\xe2@'

>>> byte2 = value[6:]
>>> print(byte2)
b'\x00\x00\x00\t\xfb\xf1'

Then convert the bytes back into ints:

>>> num1 =  int.from_bytes(byte1, byteorder='big')
>>> print(num1)
123456

>>> num2 =  int.from_bytes(byte2, byteorder='big')
>>> print(num2)
654321

Then add back into a list:

>>> nums = [num1, num2]
>>> print(nums)
[123456, 654321]
Daniel T
  • 511
  • 2
  • 6