java - 在java中读取c++字节位域

标签 java c++ byte bit-fields

我有一些遗留系统,它使用 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/

相关文章:

Java 变量转换

java - 将命令行参数传递给 rbenv 中的 ruby

java - 无法使用 Spring Security 实现 CustomAuthenticationProvider : BeanCreationException while autowiring

c++ - VBO 的 std::vector 偏移量计算?

C++ 链接 header /主要错误

C# 字节数组 - 有符号和无符号的困境

java - 从服务器端(Java)向 Facebook 用户发送消息

java - MapDB集合大小问题

c++ - 如何在 mac os 中录制系统声音,如 Wondershare Filmora Scrn?

php - 如何从php发送字节数组