Ruby unpack binary

亡梦爱人 提交于 2021-01-28 11:23:55

问题


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).

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

Thx in advance!


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/55125275/ruby-unpack-binary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!