5

そのため、既知の量のバイトを解析しています。ただし、最初の 2 バイトは何らかの数値を表し、次のバイトは 1 バイトのみの数値を表しますが、次の 4 バイトすべてが 1 つの大きな数値を表している可能性があります。私の方法以外に、データを解析するためのより良い方法はありますか。

    switch (i) {
            //Status
            case 2:
                temp[3] = bytes[i];
                break;
            case 3:
                temp[2] = bytes[i];
                ret.put("Status", byteArrayToInt(temp).toString());
                break;
            //Voltage
            case 4:
                temp[3] = bytes[i];
                break;
            case 5:
                temp[2] = bytes[i];
                ret.put("Voltage", byteArrayToInt(temp).toString());
                break;
            //Lowest Device Signal
            case 6:
                temp[3] = bytes[i];
                break;
            case 7:
                temp[2] = bytes[i];
                ret.put("Lowest Device Signal", byteArrayToInt(temp).toString());
                clearBytes(temp);
                break;

}

私はバイトの配列をループしており、どのバイトがどの場所に行くかを知るスイッチがあります。たとえば、2 番目と 3 番目のバイトがステータス コードに行くことを知っています。だから私はそれらを取り、それらをintに結合します。temp バイト配列は byte[] temp = new byte[4] です。これを行うより良い方法はありますか?

4

2 に答える 2

11

ByteBufferはこれを処理できます。

byte[] somebytes = { 1, 5, 5, 0, 1, 0, 5 };
ByteBuffer bb = ByteBuffer.wrap(somebytes);
int first = bb.getShort(); //pull off a 16 bit short (1, 5)
int second = bb.get(); //pull off the next byte (5)
int third = bb.getInt(); //pull off the next 32 bit int (0, 1, 0, 5)
System.out.println(first + " " + second + " " + third);

Output
261 5 65541

メソッドを使用して任意のバイト数をget(byte[] dst, int offset, int length)取得し、そのバイト配列を必要なデータ型に変換することもできます。

于 2013-08-01T19:38:04.357 に答える