Why hex & # 8594; base64 is so different from base64 & # 8594; hex using package and unpack?

I got this code that converts from hex to base64 and vice versa. I got to_base64 from another SO question, and I wrote to_hex with some guesses, trial and error.

 class String def to_base64 [[self].pack("H*")].pack("m0") end def to_hex self.unpack("m0").first.unpack("H*").first end end 

But I really do not find the pack and unpack methods even after reading the documents. In particular, the asymmetry between the two implementations confuses me. In theory, in both cases we take a string encoded in some database (16 or 64), and we want to convert it to another database. So why can't we implement to_hex like this:

 def to_hex [[self].pack("m0")].pack("H*") end 

or to_base64 using unpack ? Why does the base we choose completely change the method that we must use to perform the transformations?

+6
source share
1 answer

to_hex is the exact opposite of to_base64 :

to_base64

  • put string in array: [self]
  • call package with H* : [self].pack("H*")
  • put the string in an array: [[self].pack("H*")]
  • call package with m0 : [[self].pack("H*")].pack("m0")

to_hex

  • unzip call using m0 : self.unpack("m0")
  • extract string from array: self.unpack("m0").first
  • Unpack the call using H* : self.unpack("m0").first.unpack("H*")
  • extract string from array: self.unpack("m0").first.unpack("H*").first

The way you canceling operations using reverse operations:

 a = 5 (a + 4) * 3 #=> 27 

And vice versa:

 a = 27 (a / 3) - 4 #=> 5 

a.pack is the inverse of a.unpack , and a.first is the inverse of [a]

+11
source

Source: https://habr.com/ru/post/954285/


All Articles