Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient arbitrary-sized integer packing in Python

Tags:

python

byte

The struct.pack() function allows converting integers of up to 64 bit to byte strings. What's the most efficient way to pack an even larger integer? I'd rather not add a dependency on non-standard modules like PyCrypto (which provides num_to_bytes()).

like image 303
noamtm Avatar asked Apr 22 '09 14:04

noamtm


People also ask

How does Python handle large integers?

In Python, there is no integer overflow problem; therefore, Python programmers do not need to worry about what variable type to use for each integer. Python allows programmers to manipulate huge numbers without having to worry about precision loss.

What is int16 in Python?

int16. A 16-bit signed integer whose values exist on the interval [−32,767, +32,767] .

What is the size of int data type in Python?

These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.)

How does Python store big numbers?

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.


1 Answers

Came across the same issue. Starting from python 3.2, you can use int.to_bytes:

>>> (2**100).to_bytes(16, byteorder='big')
b'\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
like image 127
Claudio Avatar answered Oct 07 '22 00:10

Claudio