I am confused on how to convert short
array to byte
array.
E.g. I have the follwoing short
array
short[] shrt_array = new short[]{ 0x4 , 0xd7 , 0x86, 0x8c, 0xb2, 0x14, 0xc, 0x8b, 0x2d, 0x39, 0x2d, 0x2d, 0x27, 0xcb, 0x2e, 0x79, 0x46, 0x36, 0x9d , 0x62, 0x2c };
By using this link Converting short array to byte array the two methods of conversion, I get the following two different byte
arrays:
expectedByteArray = new byte[] {
(byte) 0x4, (byte) 0xd7, (byte) 0x86,
(byte) 0x8c, (byte) 0xb2, (byte) 0x14,
(byte) 0xc, (byte) 0x8b, (byte) 0x2d,
(byte) 0x39, (byte) 0x2d, (byte) 0x2d,
(byte) 0x27, (byte) 0xcb, (byte) 0x2e,
(byte) 0x79, (byte) 0x46, (byte) 0x36,
(byte) 0x9d, (byte) 0x62, (byte) 0x2c,
(byte) 0x0, (byte) 0x0, (byte) 0x0,
(byte) 0x0, (byte) 0x0, (byte) 0x0,
(byte) 0x0, (byte) 0x0, (byte) 0x0,
(byte) 0x0, (byte) 0x0, (byte) 0x0,
(byte) 0x0, (byte) 0x0, (byte) 0x0,
(byte) 0x0, (byte) 0x0, (byte) 0x0,
(byte) 0x0, (byte) 0x0, (byte)0x0};
Second result: `
expectedByteArray = new byte[] {
(byte) 0x4, (byte) 0x0, (byte) 0xd7,
(byte) 0x0, (byte) 0x86, (byte) 0x0,
(byte) 0x8c, (byte) 0x0, (byte) 0xb2,
(byte) 0x0, (byte) 0x14, (byte) 0x0,
(byte) 0xc, (byte) 0x0, (byte) 0x8b,
(byte) 0x0, (byte) 0x2d, (byte) 0x0,
(byte) 0x39, (byte) 0x0, (byte) 0x2d,
(byte) 0x0, (byte) 0x2d, (byte) 0x0,
(byte) 0x27, (byte) 0x0, (byte) 0xcb,
(byte) 0x0, (byte) 0x2e, (byte) 0x0,
(byte) 0x79, (byte) 0x0, (byte) 0x46,
(byte) 0x0, (byte) 0x36, (byte) 0x0,
(byte) 0x9d, (byte) 0x0, (byte) 0x62,
(byte) 0x0, (byte) 0x2c, (byte) 0x0};
`
Can you help me which is the right one.
Your use of asShortBuffer
was somewhat close. It should be:
ByteBuffer buffer = ByteBuffer.allocate(shrt_array.length * 2);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.asShortBuffer().put(shrt_array);
byte[] bytes = buffer.array();
Doing it manually for explicit control of byte order:
byte[] tobytes(short[] shorts, boolean bigendian) {
int n = 0;
byte[] bytes = new byte[2*shorts.length];
for (n=0; n < shorts.length; n++) {
byte lsb = shorts[n] & 0xff;
byte msb = (shorts[n] >> 8) & 0xff;
if (bigendian) {
bytes[2*n] = msb;
bytes[2*n+1] = lsb;
} else {
bytes[2*n] = lsb;
bytes[2*n+1] = msb;
}
}
return bytes;
}
If s
is the short value, you have least significant byte with s & 0xff
and most significant byte as (s >> 8) & 0xff
. You can put them at byte array index 2*n
and 2*n+1
in the order you want, where n
is the index in the short array.
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