4
myNumber=$(date +%s) # big number in decimal
myNumberInB58=$(toBase58 $myNumber)

toBase58() {
  # <your answer here>
}

What is the most elegant and/or concise way to encode an integer in Base58?

Elifarley
  • 1,310
  • 3
  • 16
  • 23

3 Answers3

7

The bitcoin-bash-tools provide the functions {en,de}codeBase58:

decodeBase58() {
    echo -n "$1" | sed -e's/^\(1*\).*/\1/' -e's/1/00/g' | tr -d '\n'
    dc -e "$dcr 16o0$(sed 's/./ 58*l&+/g' <<<$1)p" |
    while read n; do echo -n ${n/\\/}; done
}

encodeBase58() {
    echo -n "$1" | sed -e's/^\(\(00\)*\).*/\1/' -e's/00/1/g' | tr -d '\n'
    dc -e "16i ${1^^} [3A ~r d0<x]dsxx +f" |
    while read -r n; do echo -n "${base58[n]}"; done
}

Those work with the fields dcr and base58 defined directly above in the file.

Uroc327
  • 1,379
  • 2
  • 10
  • 28
1

Would this do?

a=( {1..9} {A..H} {J..N} {P..Z} {a..k} {m..z} )
toBase58() {
    # TODO: check that $1 is a valid number
    local nb=$1 b58= fiftyeight=${#a[@]}
    while ((nb)); do
        b58=${a[nb%fiftyeight]}$b58
        ((nb/=fiftyeight))
    done
    printf '%s\n' "$b58"
}
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
0

Here's another version:

# Order-Preserving Base58 (OPB58).
# Also supports negative numbers.
int2b58() {
  # Omit IOlo
  local n="$1" i BASE58=$(echo {0..9} {A..H} {J..N} {P..Z} {a..k} {m..n} {p..z} | tr -d ' ')
  ((n < 0 )) && printf -- '-' && n=$((-n))
  for i in $(echo "obase=58; $n" | bc); do
    printf ${BASE58:$(( 10#$i )):1}
  done; echo
}
Elifarley
  • 1,310
  • 3
  • 16
  • 23