如何在 Java 中解析字节数组中的位字段?
我承担了一项艰巨的任务,即将来自源的一些传入 UDP 数据包解析为适当的 Java 表示形式。问题在于数据包中保存的数据不是字节对齐的。为了使协议尽可能严格,有许多位字段指示数据字段的存在或不存在。
例如,在位索引 34 处,您可能会发现应转换为浮点数的 24 位字段。位索引110可以是指示接下来的3个字段各自是包含一天中的小时、分钟和秒的5和6位值的标志。 (这些只是我编造的,但代表了规范的内容)。这些数据包可能有几百位长。
该规范不太可能改变,但完全有可能我会被要求解码其他类似的数据包格式。
我当然可以根据需要进行位移和屏蔽,但我担心最终会陷入位移地狱,然后在发现更多数据包格式时淹没在其中。
我很想听听有关最佳实践或 Java 库的任何建议,这些建议可以使任务更易于管理。
I've been given the arduous task of parsing some incoming UDP packets from a source into an appropriate Java representation. The kicker is the data held within the packets are not byte aligned. In an effort to make the protocol as tight as possible, there are a number of bit fields indicating the presence or absence of data fields.
For example, at bit index 34 you may find a 24 bit field that should be converted to a float. Bit index 110 may be a flag indicating that the next 3 fields are each 5 and 6 bit values containing the hour, minute, and second of the day. (These are just made up by me but are representative of what the spec says). These packets are probably a few hundred bits long.
The spec is not likely to change, but it's completely possible that I'll be asked to decode other similar packet formats.
I can certainly bit shift and mask as needed, but I'm worried about ending up in bit shift hell and then drowning in it when more packet formats are discovered.
I'd love to hear any suggestions on best practices or Java libraries that may make the task more manageable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解码 QR 码与一次读取几个位的练习大致相同,完全不对齐。这是我写的来处理它的——也许你可以重用它。
http: //code.google.com/p/zxing/source/browse/trunk/core/src/com/google/zxing/common/BitSource.java
Decoding QR codes is much the same exercise in reading a couple bits at a time, completely unaligned. Here's what I wrote to handle it -- maybe you can just reuse this.
http://code.google.com/p/zxing/source/browse/trunk/core/src/com/google/zxing/common/BitSource.java
对于这种情况,我开发了 JBBP 库,可以在 Maven 中心访问
例如,将文件解析为位并打印解析值看起来像
for such cases I have developed JBBP library which is accessible in Maven central
for instance parsing of file to bits and printing of parsed values looks like