-1

我需要将字节数组转换为短数组。我不知道为什么它不起作用!这是我的代码:

private short[] byte2short(byte[] buffer) {
   int byteArrsize = buffer.length;
   short[] shorts = new short [ byteArrsize/2];

   for (int i = 0; i < byteArrsize; i++) {

       short MSB = (short) buffer[2*i+1];
       short LSB = (short) buffer[2*i];
       shorts[i] = (short) (MSB << 8 | (255 & LSB));

    }

    return shorts;
}         
4

2 回答 2

1

您是否考虑过为此使用 Java 内置的库?

private short[] byte2short(byte[] buffer) {
    ByteBuffer bytes = ByteBuffer.wrap(buffer);
    ShortBuffer shorts = bytes.asShortBuffer();
    return shorts.array();
}

看起来数组方法asShortBuffer()可能无法按计划进行。但是手动转储它们很简单:

private short[] byte2short(byte[] src) {
    short[] dest = new short[src.length / 2];
    ByteBuffer.wrap(src).asShortBuffer().get(dest);
    return dest;
}
于 2013-07-12T15:54:48.957 回答
0

你可以试试这个(来自https://groups.google.com/forum/#!topic/android-developers/HAI2OQW9arA):

private short[] byte2short(byte[] byteD) 
{
   int byteArrsize = byteD.length / 2;
   short[] shorts = new short[byteArrsize];
   for (int i = 0; i < byteArrsize; i++) {
       shorts[i] = (short) (byteD[i * 2] + (byteD[(i * 2) + 1] << 8));
   }
   return shorts;
}
于 2013-07-12T15:54:16.190 回答