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?
Jonah source share