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

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

问题描述

我使这段代码正常工作,将其从十六进制转换为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

但是,即使在阅读了文档之后,我也不真正使用packunpack方法.具体来说,我对两个实现之间的不对称感到困惑.从概念上讲,在两种情况下,我们都采用以某个基数(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_hexto_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

  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.packa.unpack的逆,而a.first[a]

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

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