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

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.