Ruby:拆分二进制数据 [英] Ruby: Split binary data

查看:109
本文介绍了Ruby:拆分二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将data拆分为8154个字节的块:

I want to split data to chunks of let's say 8154 byte:

data = Zlib::Deflate.deflate(some_very_long_string)

做到这一点的最佳方法是什么?

What would be the best way to do that?

我试图用这个:

chunks = data.scan /.{1,8154}/

...但是数据丢失了! datasize为11682,但是当遍历每个块并汇总size时,我的总大小为11677.丢失了5个字节!为什么?

...but data was lost! data had a size of 11682, but when looping through every chunk and summing up the size I ended up with a total size of 11677. 5 bytes were lost! Why?

推荐答案

正则表达式不是解析二进制数据的好方法.使用byteseach_slice操作字节.并使用pack 'C*'将它们转换回字符串以进行输出或调试:

Regexps are not a good way to parse binary data. Use bytes and each_slice to operate bytes. And use pack 'C*' to convert them back into strings for output or debug:

irb> data = File.open("sample.gif", "rb", &:read)
=> "GIF89a\r\x00\r........."

irb> data.bytes.each_slice(10){ |slice| p slice, slice.pack("C*") }
[71, 73, 70, 56, 57, 97, 13, 0, 13, 0]
"GIF89a\r\x00\r\x00"
[247, 0, 0, 0, 0, 0, 0, 0, 51, 0]
"\xF7\x00\x00\x00\x00\x00\x00\x003\x00"
...........

这篇关于Ruby:拆分二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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