[java] byte配列を連結する

Javaでbyte配列 (byte[]) 同士を連結してbyte配列を作成する方法です。
forで回さなくても。System.arraycopyを使えば簡単にコピーできます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static void main(String args[]) {
 
    byte[] first  = new byte[]{(byte)0x01, (byte)0x02};
    byte[] second = new byte[]{(byte)0x1A, (byte)0x2B, (byte)0x3B};
 
    byte[] destination = new byte[first.length + second.length];
 
    System.arraycopy(first, 0, destination, 0, first.length);
    System.arraycopy(second, 0, destination, first.length, second.length);
 
    System.out.println(bytesToHex(destination));
}
 
// byte配列を文字列に変換
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

この記事を書くときに、新しいMacにJDKが入っていないことに気づいて1.9をインストールしました。
その後、javaのファイルを開くとなぜかVimが起動しなくなったり、不安定になりましたが入れているプラグインをアップデートしたら普通に開けるようになりました。

0 件のコメント :

コメントを投稿