user1090694
user1090694

Reputation: 639

int to bufferbyte

I have the following:

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

but it puts the bytes at the beggining of the array and not to the end of it how do i put it to the end? I've tried the following too:

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

but seems to work with some numbers, but in others get an ArrayIndexOutOfBoundsIndexException (they are lower than 216)

Upvotes: 0

Views: 204

Answers (2)

Guido Simone
Guido Simone

Reputation: 7952

As stated earlier ByteBuffer.putInt will always write 4 bytes. So how about

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

The following program shows the difference:

  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));

which prints out the following:

N at start: 00000063000000000000000000000000 
N at end:   00000000000000000000000000000063

Upvotes: 0

Jon Lin
Jon Lin

Reputation: 143876

it puts the bytes at the beggining of the array and not to the end of it how do i put it to the end? I've tried the following too:

Here's where the problem is. Although you call ByteBuffer.allocate(16), this just sets the capacity to 16, your buffer is still empty. So when you try to add something at index 15, there's nothing there and you get an ArrayIndexOutOfBoundsException, because the buffer's size is still 0 and you are accessing index 15. You can't write to the end of the buffer until it's filled up to that index.

Upvotes: 1

Related Questions