I have two longs representing the most and least significant bytes of a UUID respectively. How can I use Ruby to convert these two longs into a 32-character hex representation?
我有两个long分别表示UUID的最高和最低有效字节。如何使用Ruby将这两个long转换为32个字符的十六进制表示?
1 个解决方案
#1
Try using the %
string format operator like "%016x"
(sixteen zero padded hex digits):
尝试使用%string格式运算符,如“%016x”(十六个零填充十六进制数字):
a = 0xCAFEBABECAFEBABE # => 14627333968358193854
b = 0xDEADBEEFDEADBEEF # => 16045690984833335023
'%016x%016x' % [a, b] # => "cafebabecafebabedeadbeefdeadbeef"
There are many ways to insert the dashes at the right places if you want to get a properly formatted UUID string; here's the first one that comes to mind:
如果要获取格式正确的UUID字符串,有很多方法可以在正确的位置插入破折号;这是我想到的第一个:
def longs_to_uuid(a, b)
s = '%016x%016x' % [a, b]
s.scan(/(.{8})(.{4})(.{4})(.{4})(.{12})/).first.join('-')
end
longs_to_uuid(1,2) # => "00000000-0000-0001-0000-000000000002"
Don't forget to consider endianness if that's a concern...
如果这是一个问题,不要忘记考虑字节序...
#1
Try using the %
string format operator like "%016x"
(sixteen zero padded hex digits):
尝试使用%string格式运算符,如“%016x”(十六个零填充十六进制数字):
a = 0xCAFEBABECAFEBABE # => 14627333968358193854
b = 0xDEADBEEFDEADBEEF # => 16045690984833335023
'%016x%016x' % [a, b] # => "cafebabecafebabedeadbeefdeadbeef"
There are many ways to insert the dashes at the right places if you want to get a properly formatted UUID string; here's the first one that comes to mind:
如果要获取格式正确的UUID字符串,有很多方法可以在正确的位置插入破折号;这是我想到的第一个:
def longs_to_uuid(a, b)
s = '%016x%016x' % [a, b]
s.scan(/(.{8})(.{4})(.{4})(.{4})(.{12})/).first.join('-')
end
longs_to_uuid(1,2) # => "00000000-0000-0001-0000-000000000002"
Don't forget to consider endianness if that's a concern...
如果这是一个问题,不要忘记考虑字节序...