'Python built-in base-256 to base-10 conversion and vice versa?
I want to store large numbers (200-300 digits +) in a text file, so I want to know if there is either a built-in function that converts base-10 numbers to base-256 equivalents and vice versa in Python, or whether there is a module that supports this (much like the default hex() function).
Solution 1:[1]
'Base256' is essentially binary bytes. While one can interpret the result as latin-1 encoded text, that does not seem as much use. So I would not suffix the resulting file as .txt.
That aside, the struct
module us used to convert data to and from bytes. A relatively simple example:
>>> import struct
>>> b = struct.pack('HhL', 33333, -33, 3333333333)
>>> b
b'5\x82\xdf\xffU\xa1\xae\xc6'
>>> struct.unpack('HhL', b)
(33333, -33, 3333333333)
When writing to or reading from a file, remember to open in binary mode.
Solution 2:[2]
Integers have the to_bytes
-method:
base256 = number.to_bytes((number.bit_length()+7)//8, 'big')
number =int.from_bytes(base256, 'big')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Terry Jan Reedy |
Solution 2 | Serge Stroobandt |