The command below converts a decimal integer to radix 64. It does not use the Base64 encoding scheme, but it uses the characters used by the URL-safe variant of the Base64 encoding scheme as digits.
awk 'NR==FNR{a[NR-1]=$0;next}{if($0==0){print"A";next}o="";for(n=$0;n!=0;n=int(n/64))o=a[n%64]o;print o}' <(printf %s\\n {A..Z} {a..z} {0..9} - _) -
The command below does the same in Bash. It also works with Zsh if you replace l%64
with l%64+1
.
unset a;a=({A..Z} {a..z} {0..9} - _);while IFS= read l;do if ((l==0));then echo A;continue;fi;o=;for ((;l!=0;l/=64));do o=${a[l%64]}$o;done;printf %s\\n "$o";done
This converts radix 64 to decimal:
awk 'NR==FNR{a[$0]=NR-1;next}{o=0;for(i=NF;i>=1;i--)o+=a[$i]*64^(NF-i);print o}' FS= <(printf %s\\n {A..Z} {a..z} {0..9} - _) -
This does the same in Bash:
unset a;i=0;declare -A a;for x in {A..Z} {a..z} {0..9} - _;do a[$x]=$((i++));done;while IFS= read l;do o=0;for((i=${#l};i>=1;i--));do let o+=${a[${l:i-1:1}]}*64**(${#l}-i);done;echo "$o";done
The awk
commands result in loss of precision with 2**53+1
and larger numbers, but to avoid it you can add -M
(--bignum
) in gawk
4.1 and later.
The Bash commands result in integer overflow with 2**63
and larger numbers.