0

長さ256バイトのバイト配列を送信したいのですが、128バイトの文字列で、別の文字列と同じ長さでなければなりません(長さはテスト目的のためだけです)。

これは私のコードです:

public void packetCompose(String user, String password) {
    //insert user in 128 bytes length, same with password 
    //and make a 256 length byte array to send
    byte[] userBytes = user.getBytes();
    byte[] passwordBytes = password.getBytes();
    byte[] buf = new byte[256];
}

必要以上のバイトがある場合でも、userBytes を 128 バイトの長さにしたいのですが、passwordBytes と同じです。次に、buf を userBytes の後に passwordBytes のようにします。

助言がありますか?前もって感謝します

4

1 に答える 1

3

バイトを宛先buf配列にコピーするだけです。

System.arraycopy( userBytes    , 0, buf,   0, Math.min( userBytes.length, 128 ) );
System.arraycopy( passwordBytes, 0, buf, 128, Math.min( userBytes.length, 128 ) );
于 2012-12-01T12:12:21.507 に答える