更新时间:2022-06-11 05:34:12
在评论中澄清你的问题(与标题无关):
Answering your question as clarified in comments (which has nothing to do with the title):
我需要将字符串编码/解码为Base58
I need to encode/decode a string to Base58
编辑:现在作为一个类(使用base58 gem):
now as a class (using base58 gem):
require 'base58'
class Base58ForStrings
def self.encode(str)
Base58.encode(str.bytes.inject { |a, b| a * 256 + b })
end
def self.decode(b58)
b = []
d = Base58.decode(b58)
while (d > 0)
d, m = d.divmod(256)
b.unshift(m)
end
b.pack('C*').force_encoding('UTF-8')
end
end
Base58ForStrings.encode('Hello こんにちは')
# => "5scGDXBpe3Vq7szFXzFcxHYovbD9c"
Base58ForStrings.decode('5scGDXBpe3Vq7szFXzFcxHYovbD9c')
# => "Hello こんにちは"
适用于任何UTF-8字符串。
Works for any UTF-8 string.