base_coder.py

Created by zetamap

Created on March 19, 2024

442 Bytes

Simple library to encode and decode int values to any encoding base between 2 and 64.

Content

encode(v: the value, b: encoding base ): Encode the value in the specified encoding base, return None if base is not valid.

decode(v: the value, b: encoding base ): Decode the encoded value in the specified encoding base, return None if base is not valid or if value is an empty string.

CHARSET: The list of characters that define the encoding, add your own characters to increase the encoding base.

CHARS: The maximum possible encoding base, must be increased if you add new characters in CHARSET.


CHARSET=''.join([chr(c+48+(c>9)*39-(c>35)*58)for c in range(62)])+'_@'
CHARS=len(CHARSET)
def encode(v,b):
 if b<2 or b>CHARS:return
 if v<0:return '-'+encode(-v,b)
 o=(v==0)*"0"
 while v:o,v=CHARSET[v%b]+o,v//b
 return o
def decode(v,b):
 if not v or b<2 or b>CHARS:return
 if b<37:return int(v,b)
 if v[0]=='-':return -decode(v[1],b)
 o,s=0,len(v)
 for i,l in enumerate(v):o+=CHARSET.index(l,0,b)*(b**(s-(i+1)))
 return o