Bash decimal to base conversion 62

I would like to cancel the operation performed by the following bash command:

 $ echo $((62#a39qrT)) 9207903953 

i.e. convert the decimal number 9207903953 to base 62, preserving the bash standard {0..9},{a..z},{A..Z} .

I know I can do this using bc , but I will have to manually convert each character. For example, I am doing this currently:

 BASE62=($(echo {0..9} {a..z} {A..Z})) for i in $(echo "obase=62; 9207903953" | bc) do echo -n ${BASE62[$i]} #Doesn't work if bc output contains leading zeroes done 

There must be a way to do this in a less "hacky" way. Do you know how to do this more efficiently?

EDIT: changed input bc .

+6
source share
4 answers

I really appreciate the solution you came across, and I believe that this is not the case directly with bash. Here is a little thought you missed:

 BASE62=($(echo {0..9} {a..z} {A..Z})) for i in $(bc <<< "obase=62; 9207903953"); do echo -n ${BASE62[$(( 10#$i ))]} done && echo 

Conclusion:

 a39qrT 
+6
source
 function base62encode() { bc<<<"obase=62;$1" | awk '{for (i=1; i<=NF; i++) printf "%c", $i+(($i<10)?48:(($i<36)?87:29))}' } 
  • bc<<<"obase=62;$1" converted to a sequence of spaces prefixed with decimal numbers from 00 to 61
  • then shifts each digit to an ASCII table and converts it to a character with awk printf

Or without a for loop:

 function base62encode() { bc<<<"obase=62;$1" | awk 'BEGIN{RS=" +"}/./{printf "%c", $1+(($1<10)?48:(($1<36)?87:29))}'; } 
+1
source

Or without bc and with an arbitrary base:

 function baseXencode() { awk 'BEGIN{b=split(ARGV[1],D,"");n=ARGV[2];do{d=int(n/b);i=D[nb*d+1];r=ir;n=d}while(n!=0);print r}' "$1" "$2" } function base62encode() { baseXencode 0123465789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "$1" } 
0
source

Any base10 to baseX conversion function using gforth and tr , ( tr is required since gforth and bash use different characters to print the bases):

 n2b() { gforth -e "$1 $2 base ! . cr bye" | tr '[0-9A-z]' '[0-9a-zA-Z]' ; } n2b 9207903953 62 n2b 9207903953 61 # Also works with other bases. n2b 9207903953 3 

Conclusion:

 a39qrT aT1PM8 212202201021222121202 
0
source

All Articles