| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

「Java byte配列を16進数文字列に変換する」の版間の差分

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
 
1行目: 1行目:
==Java byte配列を16進数文字列に変換する==
+
==[[Java byte配列を16進数文字列に変換する]]==
 
[[Java]] |  
 
[[Java]] |  
  

2020年2月16日 (日) 04:27時点における最新版

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();
}