Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Python int into a big-endian string of bytes

Tags:

python

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?

like image 569
fish Avatar asked May 10 '09 20:05

fish


People also ask

How do you convert int to byte in Python?

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.

How do you convert little-endian to big-endian?

"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.

Does Python use big-endian?

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.


1 Answers

In Python 3.2+, you can use int.to_bytes:

If you don't want to specify the size

>>> n = 1245427 >>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0' b'\x13\x00\xf3' 

If you don't mind specifying the size

>>> (1245427).to_bytes(3, byteorder='big') b'\x13\x00\xf3' 
like image 117
Janus Troelsen Avatar answered Oct 05 '22 13:10

Janus Troelsen