2

私がやろうとしているのは、現在配列にある 4 バイトを 1 バイト変数に配置することです。例えば:

public myMethod()
{
   byte[] data = {(byte) 0x03, (byte) 0x4C, (byte) 0xD6, (byte) 0x00 };
   writeData(testMethod((byte)0x4C, data));
}

public byte[] testMethod(byte location, byte[] data)
{
    byte[] response = {(byte) 0x00, (byte) 0x21, location, data);
    return response;
}

バイトをバイト[]にキャストできないため、これは明らかに機能しません。

何か案は?

編集:私が求めていることについて、いくつかの混乱があります。私が探しているのは

data = (byte) 0x034CD600;

「testMethod」で。

4

2 に答える 2

2

あなたはそのようなことを試すことができます:

private static final byte[] HEADER = new byte[] { (byte) 0x00, (byte) 0x21 };

public static byte[] testMethod(byte location, byte[] data) {
    byte[] response = Arrays.copyOf(HEADER, HEADER.length + data.length + 1);
    response[HEADER.length] = location;
    System.arraycopy(data, 0, response, HEADER.length + 1, data.length);
    return response;
}

ByteBufferまたはsを使用している場合

public static ByteBuffer testMethodBB(ByteBuffer bb, byte location, byte[] data) {
    if(bb.remaining() < HEADER.length + 1 + data.length) {
        bb.put(HEADER);
        bb.put(location);
        bb.put(data);
        bb.flip();
        return bb;
    }
    throw new IllegalStateException("Buffer overflow!");
}
于 2013-09-06T17:29:53.227 に答える
0

byte[]からの要素を格納するのに十分な大きさの を作成するだけdataです。

public byte[] testMethod(byte location, byte[] data)
{
    byte[] response = new byte[3 + data.length];
    response[0] = (byte) 0x00;
    response[1] = (byte) 0x21;
    response[2] = location;
    for (int i = 0; i < data.length; i++) {
        response[3 + i] = data[i];
    }
    return response;
}

System.arraycopy()速度が重要な場合に使用します。上記の方が分かりやすいと思います。

表記

byte[] response = {(byte) 0x00, (byte) 0x21, location, date);

おっしゃる通り違法です。初期化子は、 typeの{...}変数またはリテラルのみを受け入れますbyte

于 2013-09-06T17:16:56.107 に答える