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();
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With