ByteBuffer api给出错误的整数值

时间:2011-11-01 12:23:13

标签: java bytebuffer

我正在使用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时,我得到一个不同的整数值。 知道问题出在哪里? 谢谢!

2 个答案:

答案 0 :(得分:3)

代码可以正常工作,如果确实选择索引为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

一些注意事项:

  • 请记住,endian可能因系统而异(如果这是协议的一部分,请检查两台主机上的endian)
  • 您从bbf.array()调用获得的数组是支持数组,即:

      

    对此缓冲区内容的修改将导致返回的数组内容被修改,反之亦然。

答案 1 :(得分:1)

据我所见,B位于偏移1