如何在shell脚本中将十进制数转换为Base58

tez616oj  于 2023-02-24  发布在  Shell
关注(0)|答案(3)|浏览(129)
myNumber=$(date +%s) # big number in decimal
myNumberInB58=$(toBase58 $myNumber)

toBase58() {
  # <your answer here>
}

Base58中对整数进行编码的最优雅和/或最简洁的方法是什么?

xjreopfe

xjreopfe1#

bitcoin-bash-tools提供函数{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
}

它们与文件中直接定义的字段dcrbase58一起工作。

djmepvbi

djmepvbi2#

这个行吗?

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"
}
khbbv19g

khbbv19g3#

下面是另一个版本:

# 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
}

相关问题