我有一些遗留系统,它使用 C++ 中的位字段生成 bytes[] 数组,该数组将通过网络发送
struct date_compressed {
unsigned int d:5; //2 bytes
unsigned int m:4; //1 bytes
unsigned int y; //4 bytes
};
This produces a hex string of 9fd3d46fde070000
我需要能够在 Java 中读取这些字节并读取正确的值,我该怎么做?
我正在查看一些 ByteBuf 库,例如 netty 等,但我找不到任何好的示例,我们该如何做到这一点。
谢谢
最佳答案
使用 ByteBuffer
,并确保正确设置字节序。
示例
byte[] data = new byte[7];
// fill data here
ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
int d = buf.getShort() & 0x1f; // 2 bytes, 5 bits, unsigned
int m = buf.get() & 0xf; // 1 byte, 4 bits, unsigned
int y = buf.getInt(); // 4 bytes, 32 bits, signed
当然,年份值是带符号的,而不是像指定的 C++ 代码那样无符号,但年份值不会那么大。
关于java - 在java中读取c++字节位域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60255153/