Reputation: 2216
Have a couple questions, first on this method, which converts an int[]
to a byte[]
:
public static byte[] intToByte(int[] input){
ByteBuffer byteBuffer = ByteBuffer.allocate(input.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(input);
byte[] array = byteBuffer.array();
return array;
}
Im making a game, and I have to send a byte array over a socket, and I like this method because it works basically, but I dont like to use anything I dont truly understand what its doing, so could you give me some insight on what this method is doing? I believe it first creates enough space for the bits, but why does it do 'times' four to the length? And is the intBuffer connected to the byteBuffer? because why do you need all the Intbuffer stuff if not.
Okay last question, whats the deal with BIG_ENDIAN
vs. LITTLE_ENDIAN
? For example, in my other method, which converts a byte array to int array, what is the benefits for including .order(BIG_ENDIAN)
?
public static int[] byteToInt(byte[] input){
IntBuffer intBuf = ByteBuffer.wrap(input).order(ByteOrder.BIG_ENDIAN).asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
return array;
}
I know BIG_ENDIAN
and LITTLE_ENDIAN
just dictate how the bytes are ordered, but why even define an endian? why not just have this?
IntBuffer intBuf = ByteBuffer.wrap(input).asIntBuffer();
Upvotes: 3
Views: 2533
Reputation: 135992
IntBuffer is an int view of the byte array of byteArray. The purpose to use IntBuffer is its put(int[]) which allows to the input int array in one go. As a matter of fact you could do without IntBuffer as
ByteBuffer byteBuffer = ByteBuffer.allocate(input.length * 4);
for(int i : input) {
byteBuffer.putInt(i);
}
...
the result would be the same.
This demonstrates the difference between BigEndian (default) and LittleEndian
int[] input = {1,2,3,4};
ByteBuffer byteBuffer = ByteBuffer.allocate(input.length * 4);
// byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
for(int i : input) {
byteBuffer.putInt(i);
}
byte[] array = byteBuffer.array();
System.out.println(Arrays.toString(array));
output
[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4]
uncomment byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
and the output will be
[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]
Upvotes: 3
Reputation: 198023
An int
takes up four bytes, so you have to allocate a byte[]
four times as long as the int[]
. asIntBuffer()
returns a view of the ByteBuffer
as an IntBuffer
, so putting the int[]
into the IntBuffer
converts all the int
s into four bytes each and puts them into the ByteBuffer
.
Endianness defines which order the four bytes of an int
are written into the ByteBuffer
.
As for your last question, an IntBuffer
is not an int[]
, nor does an IntBuffer
obtained from ByteBuffer.asIntBuffer()
support the array()
method. In other words, there is no backing int[]
to such an IntBuffer
, since the implementation is based on a byte[]
.
Upvotes: 2