Blumer
Blumer

Reputation: 5035

Convert Two Longs to a Hex String

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?

Upvotes: 0

Views: 131

Answers (1)

maerics
maerics

Reputation: 156384

Try using the % string format operator like "%016x" (sixteen zero padded hex digits):

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:

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...

Upvotes: 2

Related Questions