Java で、バイト列を文字列に変換・表示する方法

以下のメソッドを使えばよい。引数にバイト列 (byte[]) を与えると、そのバイト列を 16 進数表記に変換した文字列が返される。

public String byteToString(byte[] b) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < b.length; i++) {

    int d = b[i];
    d += d < 0 ? 256 : 0; // byte 128-255
    if (d < 16) { //0-15 16
        s.append("0");
    }
    s.append(Integer.toString(d, 16));
}
return s.toString();
}

または、以下のようにしてもよい。

public String byteToString(byte[] b) {
if (b == null || b.length <= 0) return null;
byte ch = 0x00;
String pseudo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
StringBuffer s = new StringBuffer(b.length * 2);

for(int i = 0; i < b.length; i++) {

    ch = (byte) (b[i] & 0xf0);
    ch = (byte) (ch >>> 4);
    ch = (byte) (ch & 0x0f);
    s.append(pseudo[(int) ch]);
    ch = (byte) (b[i] & 0x0f);
    s.append(pseudo[(int) ch]);
}
return s.toString();
}

Comments