int到bufferbyte

时间:2012-09-13 19:51:52

标签: java bytebuffer

我有以下内容:

byte[] l = ByteBuffer.allocate(16).putInt(N).array();

但是它将字节放在数组的开头而不是它的末尾 我怎么把它放到最后? 我也尝试了以下内容:

byte[] l = ByteBuffer.allocate(16).putInt(15 - (int)Math.ceil((Math.log(N)/Math.log(2))/8), N * 8).array();

但似乎可以使用一些数字,但在其他数字中得到一个ArrayIndexOutOfBoundsIndexException(它们低于2 16

2 个答案:

答案 0 :(得分:1)

  

它将字节放在数组的开头而不是它的末尾如何将它放到最后?我也尝试了以下内容:

这就是问题所在。虽然你打电话给ByteBuffer.allocate(16),但这只是将容量设置为16,你的缓冲区仍然是空的。因此,当您尝试在索引15处添加某些内容时,没有任何内容,并且您得到一个ArrayIndexOutOfBoundsException,因为缓冲区的大小仍为0并且您正在访问索引15.在填充到缓冲区之前,您无法写入缓冲区的末尾那个指数。

答案 1 :(得分:0)

如前所述,ByteBuffer.putInt将始终写入4个字节。那怎么样呢?

byte[] l = ByteBuffer.allocate(12).putInt(N).array();

以下程序显示了不同之处:

  int N = 99;

  byte[] l = ByteBuffer.allocate(16).putInt(N).array();
  System.out.println("N at start: " + DatatypeConverter.printHexBinary(l));

  l = ByteBuffer.allocate(16).putInt(12,N).array();
  System.out.println("N at end:   " + DatatypeConverter.printHexBinary(l));

打印出以下内容:

N at start: 00000063000000000000000000000000 
N at end:   00000000000000000000000000000063