Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting short array to byte array in JAVA

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.

like image 918
student Avatar asked Dec 11 '22 10:12

student


2 Answers

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();
like image 109
VGR Avatar answered Dec 29 '22 10:12

VGR


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.

like image 23
Ingo Avatar answered Dec 29 '22 11:12

Ingo