Ruby解压二进制文件 [英] Ruby unpack binary

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

问题描述

我正在第一次用Ruby解压缩二进制文件.已经发现解压缩方法非常有效.根据文档,它最适合8(1字节),16(2字节),32(4字节)和64位(8字节).

I am working on unpacking a binary file for the first time in Ruby. Already found the unpack method which works pretty nice. Which according to the docs works perfect for 8(1 byte),16(2 byte),32(4 byte) and 64 bit(8 byte).

但是现在我必须解压缩5个字节.我该怎么做?

But now I have to unpack 5 bytes. How do I do this?

提前谢谢!

推荐答案

从字面上解压缩五个字节: str.unpack'C5'

To literally unpack five bytes: str.unpack 'C5'

这为您提供了五个字节值作为无符号整数.问题是如何将这些int重新解释为单个数据类型.打包/解包只能识别两种尺寸的标准功率,因此您必须手动执行该操作.

That gives you five byte values as unsigned ints. The question is how to reinterpret those ints as a single data type. Pack/unpack only recognize the standard power of two sizes, so you'll have to do that part manually.

例如,要获取一个小的endian无符号40位int

For example, to get a little endian unsigned 40-bit int

bytes = str.unpack 'C5'
int = bytes.map.with_index { |byte, i| byte << (i * 8) }.reduce(:+)

如果您需要做一些更复杂的事情,例如带符号的类型或浮点数……祝您好运.

If you need to do something more sophisticated like a signed type or a float... good luck.

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

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