title: Why is hex -> base64 so different from base64 -> hex using pack and unpack?
body: <p>I got this code working, which converts from hex to base64, and vice versa.  I got <code>to_base64</code> from another SO question, and I wrote <code>to_hex</code> with some guesswork and trial and error.</p>
  
  <pre><code>class String
  
    def to_base64
      [[self].pack("H*")].pack("m0")
    end
  
    def to_hex
      self.unpack("m0").first.unpack("H*").first
    end
  end
  </code></pre>
  
  <p>But I don't really grok the <code>pack</code> and <code>unpack</code> methods, even after reading the docs.  Specifically, I'm confused by the asymmetry between the two implementations.  Conceptually, in both cases, we take a string encoded in some base (16 or 64), and we wish to convert it to another base.  So why can't we implement <code>to_hex</code> like this:</p>
  
  <pre><code>def to_hex
    [[self].pack("m0")].pack("H*")
  end
  </code></pre>
  
  <p>or <code>to_base64</code> using <code>unpack</code>?  Why does the base we chose completely change the method we need to use to accomplish conversions?</p>