python - Convert a very large base n number to bytes -


i have large number in base n (n specified user), stored array each element representing digit. u[0] highest digit, u[1] second highest, u[-1] lowest digit , on. leading zeros understood meaningless: instance, if n 8, [0, 0, 0, 4, 7, 3] equivalent [4, 7, 3] , both equal (473) in base 8, or 315 in base 10, or 13b in hex, or [1, 59] byte array.

i want convert array of bytes correspond base-256 representation of same number, minimal leading zeros. have following code so:

def base_n_to_byte_array(digits, from_base):     """ converts base n number byte array.      :param digits: digits of number, starting highest.     :param from_base: base in number given.     """      x = 0     n = len(digits)     in range(0, len(digits)):         x += digits[i] * int(math.pow(from_base, n - - 1))      min_length = max(math.ceil(math.log(x, 256)), 1)     byte_array = x.to_bytes(min_length, byteorder='big')     return byte_array 

this works smaller numbers (a few hundred digits). however, turns out math.pow pretty limited, instance if use base 8, math.pow(8, 341) highest power can get, , math.pow(8,342) fails overflowerror: math range error.

i know common way of dealing large numbers represent them floating points - in case using code encode/decode binary files alternative representations (eg. trytes). therefore, if due loss of precision less significant bytes altered, lot of data corrupted, can't use approximate power calculation - need result exact.

how can solve problem? there version of math.pow doesn't overflow? there more efficient base conversion algorithm i'm overlooking?

is there version of math.pow doesn't overflow?

try using built-in exponentiation operator, **. afaik doesn't have same limitations math.pow does.

>>> math.pow(8,342) traceback (most recent call last):   file "<stdin>", line 1, in <module> overflowerror: math range error  >>> 8**342 719077253944926363091722076315609893447190791576922629093720324630930703222003852530833909289630144084480455519485573430635159075257666489971389722557896497511071573699461941105208878404984376477812331808340023075352602729369851525895652442163308948653402042738345192959788983753918865219341425318496896548864l 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -