编码的十六进制字符串中的字节数
这可能是一个简单的问题,但我正在尝试检查编码和字节(我有一段时间没有看过)来实现二进制协议。
看起来普通字符是1个字节。但是,当您将它们编码为十六进制时,字节数会减半。
ruby-1.9.2-p180 :001 > "abcd".bytesize
=> 4
ruby-1.9.2-p180 :002 > ["abcd"].pack("H*")
=> "\xAB\xCD"
ruby-1.9.2-p180 :003 > ["abcd"].pack("H*").bytesize
=> 2
我还期望十六进制编码能出现字符 0-9 和 AF
有人可以帮助澄清这里发生了什么吗?另外,如果您能为我指出在线的一般编码的良好评论,我很乐意温习。我还没有看到任何对此的简单概述,这会很棒。
谢谢!
This is probably a simple question, but I'm trying to review encodings and bytes (which I haven't looked at in a while) to implement a binary protocol.
It looks like normal characters are 1 byte. But when you encode them in Hex, it halves the number of bytes.
ruby-1.9.2-p180 :001 > "abcd".bytesize
=> 4
ruby-1.9.2-p180 :002 > ["abcd"].pack("H*")
=> "\xAB\xCD"
ruby-1.9.2-p180 :003 > ["abcd"].pack("H*").bytesize
=> 2
I was also expecting the Hex encoding to come out with characters 0-9 and A-F
Can someone help clarify what is going on here? And also if you can point me to a good review of encodings in general that is online I would love to brush up. I haven't seen any simple overviews of this yet which would be great.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
#pack
读取给定的字符串并根据给定的格式将其转换为二进制。pack('H*')
表示您给出的字符串表示十六进制表示法,因此它将从十六进制转换字节AB
和CD
转换为二进制 (1010 1011 1100 1101
),即两个字节。尝试
["g"].pack("H*")
,其中g
不是有效的十六进制字符...#pack
reads the given string and transforms it into binary according to the given format.pack('H*')
means that the string you are giving represents hexadecimal notation, so it will convert the bytesAB
andCD
from hex into binary (1010 1011 1100 1101
), which is two bytes.Try
["g"].pack("H*")
, whereg
is not a valid hexadecimal character...