byte array to short array and back again in java

后端 未结 6 1592
时光取名叫无心
时光取名叫无心 2020-11-27 03:50

I\'m having some issues taking audio data stored in a byte array, converting it to a big-endian short array, encoding it, then changing it back into a byte array. Here is wh

相关标签:
6条回答
  • 2020-11-27 04:30
    public short bytesToShort(byte[] bytes) {
         return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
    }
    public byte[] shortToBytes(short value) {
        return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(value).array();
    }
    
    0 讨论(0)
  • 2020-11-27 04:31

    How about some ByteBuffers?

    byte[] payload = new byte[]{0x7F,0x1B,0x10,0x11};
    ByteBuffer bb = ByteBuffer.wrap(payload).order(ByteOrder.BIG_ENDIAN);
    ShortBuffer sb = bb.asShortBuffer();
    while(sb.hasRemaining()){
      System.out.println(sb.get());
    }
    
    0 讨论(0)
  • 2020-11-27 04:36
    byte[2] bytes;
    
    int r = bytes[1] & 0xFF;
    r = (r << 8) | (bytes[0] & 0xFF);
    
    short s = (short)r;
    
    0 讨论(0)
  • 2020-11-27 04:37

    It looks like you are swapping the byte order between reading the bytes in and writing them back out (unsure if this is intentional or not).

    0 讨论(0)
  • 2020-11-27 04:41

    Your code is doing little-endian shorts, not big. You've the indexing for MSB and LSB swapped.

    Since you are using big-endian shorts, you could be using a DataInputStream wrapped around a ByteArrayInputStream (and DataOutputStream/ByteArrayOutputStream) on the other end, rather than doing your own decoding.

    If you're getting every other decode working, I'd guess you've got an odd number of bytes, or an off-by-one error elsewhere which is causing your mistake to get fixed on every other pass.

    Finally, I'd step through the array with i+=2 and use MSB= arr[i] and LSB=arr[i+1] rather than multiplying by 2, but that's just me.

    0 讨论(0)
  • 2020-11-27 04:48

    I also suggest you try ByteBuffer.

    byte[] bytes = {};
    short[] shorts = new short[bytes.length/2];
    // to turn bytes to shorts as either big endian or little endian. 
    ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
    
    // to turn shorts back to bytes.
    byte[] bytes2 = new byte[shortsA.length * 2];
    ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(shortsA);
    
    0 讨论(0)
提交回复
热议问题