トップ 一覧 ping 検索 ヘルプ RSS ログイン

Java byte配列を16進数文字列に変換するの変更点

  • 追加された行はこのように表示されます。
  • 削除された行はこのように表示されます。
!!!Java byte配列を16進数文字列に変換する
[Java]

 public static String byteToString(byte[] bytes) {
    if (bytes == null) {
       return null;
    }
    
    StringBuilder buf = new StringBuilder(bytes.length * 2);
    for (int i = 0; i < bytes.length; i++) {
       int d = bytes[i];
       if (d < 0) {
          // byte型では128〜255が負値になっているので補正
          d += 256;
       }
       if (d < 16) {
          // 0〜15は16進数で1けたになるので、2けたになるよう頭に0を追加
          buf.append("0");
       }
       // 1バイトを16進数2けたで表示
       buf.append(Integer.toString(d, 16)); 
    }
    return buf.toString();
 }