为什么是十六进制-& gt; base64与base64有何不同-& gt;十六进制使用打包和解包? [英] Why is hex -> base64 so different from base64 -> hex using pack and unpack?

查看:153
本文介绍了为什么是十六进制-& gt; base64与base64有何不同-& gt;十六进制使用打包和解包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使这段代码正常工作,将其从十六进制转换为base64,反之亦然。我从另一个SO问题中得到了 to_base64 ,我写了 to_hex 并带有一些猜测和反复试验。

I got this code working, which converts from hex to base64, and vice versa. I got to_base64 from another SO question, and I wrote to_hex with some guesswork and 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

但是我不太喜欢 pack unpack 方法,即使在阅读文档后也是如此。具体来说,我对两种实现方式之间的不对称感到困惑。从概念上讲,在两种情况下,我们都采用以某个基数(16或64)编码的字符串,并希望将其转换为另一个基数。那么为什么我们不能像这样实现 to_hex

But I don't really grok the pack and unpack 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 to_hex like this:

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

to_base64 使用 unpack ?为什么我们选择的基础完全改变了完成转换所需的方法?

or to_base64 using unpack? Why does the base we chose completely change the method we need to use to accomplish conversions?

推荐答案

to_hex to_base64 的确切逆:


  1. 将字符串放入数组中: [self]

  2. 带有 H * 的呼叫包: [self] .pack( H *)

  3. 将字符串放入数组中: [[self] .pack( H *)]

  4. 带有 m0 的呼叫包: [[self] .pack( H *)]。pack( m0 )

  1. put string in an array: [self]
  2. call pack with H*: [self].pack("H*")
  3. put string in an array: [[self].pack("H*")]
  4. call pack with m0: [[self].pack("H*")].pack("m0")



to_hex



to_hex


  1. 使用 m0 调用拆包: self.unpack( m0)

  2. 从数组中提取字符串: self.unpack( m0)。first

  3. 使用 H * 进行拆包: self.unpack( m0)。first.unpack( H *)

  4. 从数组中提取字符串: self.unpack( m0)。first.unpack( H *)。first

  1. call unpack with m0: self.unpack("m0")
  2. extract string from array: self.unpack("m0").first
  3. call unpack with H*: self.unpack("m0").first.unpack("H*")
  4. extract string from array: self.unpack("m0").first.unpack("H*").first

通过应用运算,您可以撤消运算:

That's how you undo operations, by applying the inverse operations:

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

反之亦然:

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

a.pack a.unpack a.first [a]

这篇关于为什么是十六进制-& gt; base64与base64有何不同-& gt;十六进制使用打包和解包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆