I expect the code to return TPLIG0 as the base32 hex-extended value for 1 billion (1.000.000.000). Instead I get 7EDCK00= .
Here is my code:
import base64
num = 1000000000
needed_bytes = num.to_bytes((num.bit_length() + 7) // 8, byteorder='big')
result = base64.b32hexencode(needed_bytes).decode('utf-8')
print(result)
I have tried with b32hexencode, b32encode, as well as byteorder='little' and byteorder='big', but I cannot reproduce the expected result.
If I replace the division with the hardcoded number: num.to_bytes(5, byteorder='big') I can get the approximate result: 00TPLIG0 . But what is going on here??
I'm using python 3.10.7. on Windows and 3.11.0 on Ubuntu (both create same output).
num.bit_length() + 7) // 8is 4, not 5.b32hexencodepads its result with=if not a multiple of 40 bits (5 bytes) and the bits are shifted.Use
(num.bit_length() + 39) // 40 * 5to calculateneeded_bytesin multiples of 5 bytes, then strip leading zeroes to usebase64.b32hexencode()correctly:Output testing OP value and rolling over every 5-bit binary value: