2

我正在尝试将 UUIDv4 格式化为 url 友好的字符串。base16 中的典型格式很长并且有破折号:

xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx

为了避免破折号和下划线,我将使用 base58(就像比特币一样),所以每个字符都完全编码sqrt(58).floor = 7 bits

我可以将 uuid 打包成二进制文件:

[ uuid.delete('-') ].pack('H*')

要获得 8 位无符号整数,它的:

binary.unpack('C*')

如何将每 7 位解压缩为 8 位无符号整数?是否有一次扫描 7 位并将高位设置为 0 的模式?

4

2 回答 2

1
require 'base58'
uuid ="123e4567-e89b-12d3-a456-426655440000"
Base58.encode(uuid.delete('-').to_i(16))
=> "3fEgj34VWmVufdDD1fE1Su"

又回来了

Base58.decode("3fEgj34VWmVufdDD1fE1Su").to_s(16)
 => "123e4567e89b12d3a456426655440000"

从模板重建 uuid 格式的便捷模式

template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
src = "123e4567e89b12d3a456426655440000".each_char
template.each_char.reduce(''){|acc, e| acc += e=='-' ? e : src.next}  
 => "123e4567-e89b-12d3-a456-426655440000"      
于 2015-11-24T22:08:31.933 回答
1

John La Rooy's answer is great, but I just wanted to point out how simple the Base58 algorithm is because I think it's neat. (Loosely based on the base58 gem, plus bonus original int_to_uuid function):

ALPHABET = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".chars
BASE = ALPHABET.size

def base58_to_int(base58_val)
  base58_val.chars
    .reverse_each.with_index
    .reduce(0) do |int_val, (char, index)|
      int_val + ALPHABET.index(char) * BASE ** index
    end
end

def int_to_base58(int_val)
  ''.tap do |base58_val|
    while int_val > 0
      int_val, mod = int_val.divmod(BASE)
      base58_val.prepend ALPHABET[mod]
    end
  end
end

def int_to_uuid(int_val)
  base16_val = int_val.to_s(16)
  [ 8, 4, 4, 4, 12 ].map do |n|
    base16_val.slice!(0...n)
  end.join('-')
end

uuid = "123e4567-e89b-12d3-a456-426655440000"
int_val = uuid.delete('-').to_i(16)
base58_val = int_to_base58(int_val)
int_val2 = base58_to_int(base58_val)
uuid2 = int_to_uuid(int_val2)

printf <<END, uuid, int_val, base_58_val, int_val2, uuid2
Input UUID: %s
Input UUID as integer: %d
Integer encoded as base 58: %s
Integer decoded from base 58: %d
Decoded integer as UUID: %s
END

Output:

Input UUID: 123e4567-e89b-12d3-a456-426655440000
Input UUID as integer: 24249434048109030647017182302883282944
Integer encoded as base 58: 3fEgj34VWmVufdDD1fE1Su
Integer decoded from base 58: 24249434048109030647017182302883282944
Decoded integer as UUID: 123e4567-e89b-12d3-a456-426655440000
于 2015-11-25T06:59:04.613 回答