public int[] toIntArray(byte[] barr) {
//Pad the size to multiple of 4
int size = (barr.length / 4) + ((barr.length % 4 == 0) ? 0 : 1);ByteBuffer bb = ByteBuffer.allocate(size *4);
bb.put(barr);//Java uses Big Endian. Network program uses Little Endian.
bb.order(ByteOrder.LITTLE_ENDIAN);
int[] result = new int[size];
bb.rewind();
while (bb.remaining() > 0) {
result[bb.position()/4] =bb.getInt();
}return result;
}
Disappointed for not seeing shifting? Wanna complain about performance?
This is definitely not the most efficient method to convert byte array into int array yet it can be done with simple logic and a bit of knowledge in NIO.
Unless the program is to be used on 1K memory device, using ByteBuffer is acceptable I reckon.
(I tried to convert to IntBuffer but in vain. If anyone could point out, that’d be great.)
Peter has mentioned how to use with IntBuffer in comment section as follow:
public int[] toIntArray(byte[] barr) {
//Pad the size to multiple of 4
int size = (barr.length / 4) + ((barr.length % 4 == 0) ? 0 : 1);ByteBuffer bb = ByteBuffer.allocate(size *4);
bb.put(barr);//Java uses Big Endian. Network program uses Little Endian.
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.rewind();
IntBuffer ib = bb.asIntBuffer();
int [] result = new int [size];
ib.get(result);return result;
}

4 comments:
You could try
public static int[] toIntArray(byte[] barr) {
IntBuffer buffer = ByteBuffer.wrap(barr).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
int[] ints = new int[barr.length/4];
buffer.get(ints);
return ints;
}
Don't forget the padding, something like this:
int padNum = barr.length % 4;
if (padNum != 0) {
byte[] withPad = new byte[barr.length + padNum];
System.arraycopy(barr, 0, withPad, 0, barr.length);
byte[] pad = new byte[padNum];
System.arraycopy(pad, 0, withPad, barr.length, padNum);
barr = withPad;
};
Thanks, Peter. That buffer.get(ints) works. I was trying with ints[index++] = buffer.get() ;
Let me use your code in the post.
Cheers!
This post could also be titled “How to advance from a junior software developer to a senior software developer”, because no one should be promoted without mastering these simple techniques. Great post!
Post a Comment