我正在尝试将十六进制编码为 base58。它适用于 js 库base-x
十六进制 =1777c7ba65e23151ec09125011dd25c28998c70230e7b89ca6
预期的
基数 58 =AShDKgLSuCjGZr8Fs5SRLSYvmcSV7S4zwX
得到
基数 58 =cAvfov2bvPACeGktuSEtz6G526UBfCwpia1354fp5bYJwP2rhhnxqYkRcwRoDrmgqZaG
defmodule Base58 do
@alphabet '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def encode(data, hash \\ "")
def encode(data, hash) when is_binary(data) do
encode_zeros(data) <> encode(:binary.decode_unsigned(data), hash)
end
def encode(0, hash), do: hash
def encode(data, hash) do
character = <<Enum.at(@alphabet, rem(data, 58))>>
encode(div(data, 58), character <> hash)
end
defp encode_zeros(data) do
<<Enum.at(@alphabet, 0)>>
|> String.duplicate(leading_zeros(data))
end
defp leading_zeros(data) do
:binary.bin_to_list(data)
|> Enum.find_index(&(&1 != 0))
end
end