Convert Python int to byte string of a large number of bytes

I have a non-negative int, and I would like to efficiently convert it to a large-end string containing the same data. For example, int 1245427 (which is 0x1300F3) should contain a string of length 3 containing three characters whose byte values ​​are 0x13, 0x00, and 0xf3.

My ints are on a scale of 35 (base-10) digits.

How should I do it?

+49
python
May 10 '09 at 20:24
source share
8 answers

You can use the struct module:

import struct print struct.pack('>I', your_int) 

'>I' is a format string. > means big endian and I means unsigned int. Check the documentation for more format characters.

+39
May 10, '09 at 20:27
source share

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

If you do not 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 mind specifying the size

 >>> (1245427).to_bytes(3, byteorder='big') b'\x13\x00\xf3' 
+33
Oct 12 '12 at 13:15
source share

This is fast and works for small and (arbitrary) large ints:

 def Dump(n): s = '%x' % n if len(s) & 1: s = '0' + s return s.decode('hex') print repr(Dump(1245427)) #: '\x13\x00\xf3' 
+13
May 10 '09 at 20:44
source share

Probably the best way is through the built-in struct module :

 >>> import struct >>> x = 1245427 >>> struct.pack('>BH', x >> 16, x & 0xFFFF) '\x13\x00\xf3' >>> struct.pack('>L', x)[1:] # could do it this way too '\x13\x00\xf3' 

Alternatively - and I would usually not recommend this because it is error prone - you can do it "manually" by shifting and chr() :

 >>> x = 1245427 >>> chr((x >> 16) & 0xFF) + chr((x >> 8) & 0xFF) + chr(x & 0xFF) '\x13\x00\xf3' 

Out of curiosity, why do you need only three bytes? Usually you collect such an integer into a full 32 bits (C unsigned long ) and use struct.pack('>L', 1245427) , but skip step [1:] ?

+7
May 10 '09 at 20:42
source share

@Pts' answer single source Python 2/3 compatibility :

 #!/usr/bin/env python import binascii def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n & 1))) print(int2bytes(1245427)) # -> b'\x13\x00\xf3' 
+6
Feb 15 '15 at 9:33
source share
 def tost(i): result = [] while i: result.append(chr(i&0xFF)) i >>= 8 result.reverse() return ''.join(result) 
+5
May 10 '09 at 20:43
source share

Using the bitstring module:

 >>> bitstring.BitArray(uint=1245427, length=24).bytes '\x13\x00\xf3' 

Note that for this method you need to specify the bit length of the generated bit string.

Inside, this is almost the same as Alex's answer, but the module has many additional features if you want to do more with your data.

+3
Nov 21 '09 at 20:37
source share

The shortest way, I think, is the following:

 import struct val = 0x11223344 val = struct.unpack("<I", struct.pack(">I", val))[0] print "%08x" % val 

This will convert an integer to an integer with a byte.

+2
Feb 20 2018-12-12T00:
source share



All Articles