Suppose we have a number whose exact size is unknown :

>>> import random >>> a = random.randint(2**100, 2**1000) 

You need to convert it to a byte array, for example:

 >>> n = 258 >>> b = n.get_bytes(...) b'\x01\x02' >>> n = 749520 >>> b = n.get_bytes(...) b'\x0b\x6f\xd0' 

I tried to use bytes ([...]), to_bytes (...), struct.pack (...), but, as I understood in all the options, you need to specify the size of the array.

Is there anything that automatically determines the length of a number in bytes and generates a byte array?

  • Just take the logarithm of base 2 of the number - andreymal
  • Ai okay, I will also write the answer for a change - andreymal

2 answers 2

 import math n = 749520 print(n.to_bytes(math.ceil(math.log2(n) / 8), 'big')) # → b'\x0b\x6f\xd0' 

(only works for numbers greater than zero)

    Something happened, but in my opinion, this is a bicycle:

     import struct def to_bytes(n): hex_str = hex(n)[2:] if len(hex_str) % 2 == 1: hex_str = hex_str.rjust(len(hex_str) + 1, '0') numbers = [int(hex_str[i: i + 2], 16) for i in range(0, len(hex_str), 2)] return struct.pack('B' * len(numbers), *numbers) print(to_bytes(749520) == b'\x0b\x6f\xd0') # True print(to_bytes(258) == b'\x01\x02') # True import random n = random.randint(2**100, 2**1000) print(to_bytes(n))