方法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);
}