I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.
My ints are on the scale of 35 (base-10) digits.
How do I do this?
An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
"I swap each bytes right?" -> yes, to convert between little and big endian, you just give the bytes the opposite order. But at first realize few things: size of uint32_t is 32bits, which is 4 bytes, which is 8 HEX digits. mask 0xf retrieves the 4 least significant bits, to retrieve 8 bits, you need 0xff.
Python's Endianness is same as the processor in which the Python interpreter is run. The socket module of Python provides functions to handle translations of integers of different sizes from Little Endian to Big Endian and vice versa.
In Python 3.2+, you can use int.to_bytes:
>>> n = 1245427 >>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0' b'\x13\x00\xf3'
>>> (1245427).to_bytes(3, byteorder='big') b'\x13\x00\xf3'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With