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
// 8is rounded up to the nearest whole byte.x=10; x.bit_length()on the python shell on python.org and got4. Makes sense that you would need to round to the nearest whole byte.x.to_bytes(math.ceil((x+1)/256), 'little'). Feels a little more straightforward to me to just divide by the int value of a full byte and usemath.ceilthan to usebit_lengthand do shenanigans with the number of bits.//is not the "true" division but the floor division. Now it makes sense for me. For everyone didn't know the difference between true and floor division: docs.python.org/3/whatsnew/…