我正在使用 ByteBuffer API 将对象转换为字节。对象的类如下
public class Obj{
int a; // size 1 byte
int b; // size 4 bytes
int c; // size 4 bytes
}
使用 ByteBuffer API,我分配了一个对象
ByteBuffer bbf = ByteBuffer.allocate(9);
bbf.put((byte) this.getA());
bbf.putInt(this.getB());
bbf.putInt(this.getC());
byte[] msg = bbf.array();
我将 B 的值设置为 100,但是当我将字节数组从偏移量 1 转换为长度 4 时,我得到了一个不同的整数值。 知道问题出在哪里吗? 谢谢!
最佳答案
代码按预期运行,如果您确实选择了索引为 1、2、3、4 的字节,它们将产生值 100:
ByteBuffer bbf = ByteBuffer.allocate(9);
bbf.put((byte) 10);
bbf.putInt(100);
bbf.putInt(55);
byte[] msg = bbf.array();
byte[] from4to8 = Arrays.copyOfRange(msg, 1, 5);
ByteBuffer buf2 = ByteBuffer.wrap(from4to8);
System.out.println(buf2.getInt()); // Prints 100
一些注意事项:
请记住,字节序可能因系统而异(因此,如果这是协议(protocol)的一部分,请检查两台主机上的字节序)
您从
bbf.array()
调用中获得的数组是一个后备数组,即:Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa.
关于java - ByteBuffer api 给出了错误的整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7966371/