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).
Asked
Active
Viewed 4,239 times
1
-
1Is there a standard for base 256? What are the 256 symbols used to represent digits? – Denziloe Mar 16 '17 at 21:48
-
2@Denziloe then there is this - https://github.com/Parkayun/base65536 – DeepSpace Mar 16 '17 at 21:51
-
Highly related: http://stackoverflow.com/questions/3998605/efficient-binary-to-string-formatting-like-base64-but-for-utf8-utf16 (which is also almost directly related to the project linked to by @DeepSpace) – John Y Mar 16 '17 at 22:46
2 Answers
3
Integers have the to_bytes
-method:
base256 = number.to_bytes((number.bit_length()+7)//8, 'big')
number =int.from_bytes(base256, 'big')

Serge Stroobandt
- 28,495
- 9
- 107
- 102

Daniel
- 42,087
- 4
- 55
- 81
-
You can't store multiple numbers in a file like this because you wouldn't know the length when you read them. – interjay Mar 16 '17 at 22:00
-
-
it is easy to prefix such a numbers with a fixed amount of bytes for length using the other address. – Antti Haapala -- Слава Україні Sep 06 '18 at 16:11
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.

Terry Jan Reedy
- 18,414
- 3
- 40
- 52