Java byte[]字節數組轉hex16進制字符串的三種方法

方法1

這種方法代碼量是最少的,推薦

private String bytesToHex(byte[] bytes) {
    String hex = new BigInteger(1, bytes).toString(16);
}

方法2

private String bytesToHex(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
}

方法3

public String bytesToHex(byte[] bytes) {
   char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f'};  
   // 一個字節對應兩個16進制數,所以長度爲字節數組乘2
   char[] resultCharArray = new char[bytes.length * 2];  
   int index = 0; 
   for (byte b : bytes) {  
      resultCharArray[index++] = hexDigits[b>>>4 & 0xf];  
      resultCharArray[index++] = hexDigits[b & 0xf];  
   }  
   return new String(resultCharArray); 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章