为未对齐的 int 字段构造解析?
我正在使用这个漂亮的小包“construct”进行二进制数据解析。然而,我遇到了一种情况,格式定义为:
31 24 23 0
+-------------------------+
| status | an int number |
+-------------------------+
基本上,高 8 位用于状态,剩下 3 个字节用于整数:高位被屏蔽的 int 类型。我对定义格式的正确方法有点迷失:
- 强力方法是将其定义为
ULInt32
并自己进行位屏蔽 - 无论如何我可以使用 BitStruct 来省去麻烦吗?
编辑
假设 Little Endian 并基于 jterrace 的示例和 swapped=True 建议,我认为这对我的情况有用:
sample = "\xff\x01\x01\x01"
c = BitStruct("foo", BitField("i", 24, swapped=True), BitField("status", 8))
c.parse(sample)
Container({'i': 66047, 'status': 1})
谢谢
Oliver
I am using this nice little package "construct" for binary data parsing. However, I ran into a case where the format is defined as:
31 24 23 0
+-------------------------+
| status | an int number |
+-------------------------+
Basically, the higher 8 bits are used for status, and 3 bytes left for integer: an int type with higher bits masked off. I am a bit lost on what is the proper way of defining the format:
- The brute force way is to define it as
ULInt32
and do bit masking myself - Is there anyway I can use BitStruct to save the trouble?
Edit
Assuming Little Endian and based on jterrace's example and swapped=True suggestion, I think this is what will work in my case:
sample = "\xff\x01\x01\x01"
c = BitStruct("foo", BitField("i", 24, swapped=True), BitField("status", 8))
c.parse(sample)
Container({'i': 66047, 'status': 1})
Thanks
Oliver
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果构造包含 Int24 类型,这会很容易,但事实并非如此。相反,您可以自己指定位长度,如下所示:
注意:值
\x01\x01\x01
为65536 + 256 + 1 = 65793
This would be easy if construct contained Int24 types, but it doesn't. Instead, you can specify the bit lengths yourself like this:
Note: The value
\x01\x01\x01
is65536 + 256 + 1 = 65793