I am trying to convert an Integer to a byte array (array of 4 bytes) and then I will extract the last 4 bits of each byte, then I will create a short from those last 4 digits of each bytes.
I have the following code but it always prints zero.
private static short extractShort(byte[] byteArray) {
short s = 1;
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
for(int i = 0; i < byteArray.length; i++) {
byte lastFourBytes = extractLast4Bits(byteArray[i]);
// Uses a bit mask to extract the bits we are interested in
byteBuffer.put(lastFourBytes);
}
return ByteBuffer.wrap(byteBuffer.array()).getShort();
}
private static byte extractLast4Bits(byte byteParam) {
return (byte) ( byteParam & 0b00001111);
}
private static byte[] intToByteArray(int i) {
return new byte[] {
(byte)((i >> 24) & 0xff),
(byte)((i >> 16) & 0xff),
(byte)((i >> 8) & 0xff),
(byte)((i >> 0) & 0xff),
};
}
}
Any help will be sincerely appreciated