Ruby 关于字节处理

sforce100 · April 18, 2014 · Last by night_song replied at April 18, 2014 · 2472 hits

10 进制转成 16 进制字节,并不是单纯进制转换。 例如我想将 101 转成\x00\x65,应该如何处理呢??看到文档说用 pack,我这样写 [101].pack('n*'),结果却是"\x00e"

101.chr.encode 'utf-16be' # "\x00\x65"
"\x00\x65".unpack('H*').first # "0065"
"0065".gsub(/(..)/, '\x\1') # '\x00\x65'

#1 楼 @night_song 先说声谢谢,我发现

101.chr.encode 'utf-16be'

也是输出“e”,难么只是显示的问题。 另外我想问 [101].pack('n*').class => string 居然是 string 类型,难道 ruby 的 bit 也是用 string 来表示。

#2 楼 @sforce100

是显示的问题,或者你可以 101.chr.encode('utf-16be').force_encoding 'binary' 看看

ruby 是用 string 类型表示的

You need to Sign in before reply, if you don't have an account, please Sign up first.