web-dev-qa-db-ja.com

バイト配列を短い配列に戻し、再びjava

バイト配列に格納されたオーディオデータを取得し、ビッグエンディアンの短い配列に変換し、エンコードしてから、バイト配列に戻すという問題があります。これが私が持っているものです。元のオーディオデータはaudioBytes2に保存されます。代わりにcos関数でマイナスを使用してデコードに同じ形式を使用しています。残念ながら、バイトと短いデータ型の変更は交渉できません。

    short[] audioData = null;
    int nlengthInSamples = audioBytes2.length / 2;
    audioData = new short[nlengthInSamples];

    for (int i = 0; i < nlengthInSamples; i++) {
       short MSB = (short) audioBytes2[2*i+1];
       short LSB = (short) audioBytes2[2*i];
       audioData[i] = (short) (MSB << 8 | (255 & LSB));
    }

    int i = 0;
    while (i < audioData.length) {
        audioData[i] = (short)(audioData[i] + (short)5*Math.cos(2*Math.PI*i/(((Number)EncodeBox.getValue()).intValue())));
        i++;
    }

    short x = 0;
    i = 0;
    while (i < audioData.length) {
        x = audioData[i];
        audioBytes2[2*i+1] = (byte)(x >>> 0);
        audioBytes2[2*i] = (byte)(x >>> 8);
        i++;
    }

私はこの仕事をするために考えることができるすべてをしましたが、私が来た最も近いものは、他のすべてのエンコード/デコードを動作させることであり、理由はわかりません。助けてくれてありがとう。

42
Aaron

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);
82
Peter Lawrey
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();
}
9
Scott Izu

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());
}
4
Edwin Dalorzo
byte[2] bytes;

int r = bytes[1] & 0xFF;
r = (r << 8) | (bytes[0] & 0xFF);

short s = (short)r;
1
Jagadeesh

あなたのコードは、ビッグエンディアンではなく、リトルエンディアンのショートをしています。 MSBとLSBのインデックスを交換しました。

ビッグエンディアンのショートを使用しているため、独自のデコードを行うのではなく、反対側でByteArrayInputStream(およびDataOutputStream/ByteArrayOutputStream)をラップしたDataInputStreamを使用できます。

他のすべてのデコードが機能している場合、バイト数が奇数であるか、他のすべてのパスでエラーが修正される原因となっているオフバイワンエラーがあると思います。

最後に、i + = 2で配列をステップ実行し、2を掛けるのではなくMSB = arr [i]とLSB = arr [i + 1]を使用しますが、それは私だけです。

1
Matt DiMeo