1

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

W. Albuquerque
  • 315
  • 2
  • 12
  • 1
    Is 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 Answers2

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