为什么是十六进制-> base64与base64有何不同->十六进制使用打包和解包? [英] Why is hex -> base64 so different from base64 -> hex using pack and unpack?
问题描述
我使这段代码正常工作,将其从十六进制转换为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
的确切逆:
- 将字符串放入数组:
[self]
- 带有
H*
的呼叫包:[self].pack("H*")
- 将字符串放入数组中:
[[self].pack("H*")]
- 带有
m0
的呼叫包:[[self].pack("H*")].pack("m0")
- put string in an array:
[self]
- call pack with
H*
:[self].pack("H*")
- put string in an array:
[[self].pack("H*")]
- call pack with
m0
:[[self].pack("H*")].pack("m0")
to_hex
- 使用
m0
呼叫解压缩:self.unpack("m0")
- 从数组中提取字符串:
self.unpack("m0").first
- 使用
H*
调用拆包:self.unpack("m0").first.unpack("H*")
- 从数组中提取字符串:
self.unpack("m0").first.unpack("H*").first
- call unpack with
m0
:self.unpack("m0")
- extract string from array:
self.unpack("m0").first
- call unpack with
H*
:self.unpack("m0").first.unpack("H*")
- 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]
这篇关于为什么是十六进制-> base64与base64有何不同->十六进制使用打包和解包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!