int.to_bytes length calculation

Viewed 1454

Probably a stupid question but I stumbled across the int.to_bytes() function and I can't explain why I have to add "+7" if I calculate the bytes length and there is no hint in the documentation. I am sure I miss some bit/byte calculation magic but I need a little help from the community here.

Example what confused me: x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') from https://docs.python.org/3/library/stdtypes.html#int.to_bytes

Thanks in advance

1 Answers

bit_length returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros. So

x.bit_length() + 7) // 8

will just give you the number of bytes necessary to represent that integer x. You could also write something like

from math import ceil
ceil(x.bit_length / 8)

to get the same number.

The method to_bytes() requires this byte length as its first argument. To account for x == 0 you probably want to include that case to:

x.to_bytes(length=(min(x.bit_length(), 1) + 7) // 8, byteorder='little')
Related