Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Base64 encoded string to UUID format

How can I convert a Base64 encoded string to a hex encoded string with dashes(basically to uuid format)?

For example if I have

'FWLalpF2T5mmyxS03Q+hNQ0K' 

then how can I convert it to:

1562da96-9176-4f99-a6cb-14b4dd0fa135
like image 455
user3075906 Avatar asked Dec 20 '22 01:12

user3075906


1 Answers

I was familiar with unpack but this prompted me to learn the directive as pointed out by cremno.

simplest form:

b64 = 'FWLalpF2T5mmyxS03Q+hNQ0K'
b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')

#=> "1562da96-9176-4f99-a6cb-14b4dd0fa135"

b64.unpack("m0") 

give us:

#=> ["\x15b\xDA\x96\x91vO\x99\xA6\xCB\x14\xB4\xDD\x0F\xA15\r\n"]

which is an array so we use .first to grab the string and unpack again using the directive to format it in the 8-4-4-4-12 format:

b64.unpack("m0").first.unpack("H8H4H4H4H12")

gives us:

#=> ["1562da96", "9176", "4f99", "a6cb", "14b4dd0fa135"]

an array of strings, so now we just join it with the -:

b64.unpack("m0").first.unpack("H8H4H4H4H12").join('-')

#=> "1562da96-9176-4f99-a6cb-14b4dd0fa135"
like image 184
Beartech Avatar answered Jan 14 '23 16:01

Beartech