user8578740
user8578740

Reputation:

int.to_bytes length calculation

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

Upvotes: 5

Views: 4559

Answers (1)

Simon Fromme
Simon Fromme

Reputation: 3174

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, use the max function to ensure that the number of bytes is at least one:

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

Upvotes: 4

Related Questions