Java中byte转16进制字符串的方法
在Java中,将byte数组或单个byte转换为16进制字符串是一个常见的需求,以下是几种实现方法:
方法1:使用Integer.toHexString()(适用于单个byte)
public static String byteToHex(byte b) {
return String.format("%02x", b);
// 或者使用:
// return Integer.toHexString(b & 0xFF);
}
注意:直接使用Integer.toHexString(b)会得到负数的补码表示,所以需要先用& 0xFF将byte转换为无符号整数。
方法2:使用String.format()(推荐)
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
方法3:使用Apache Commons Codec库(最简单)
如果项目中可以使用第三方库,这是最简单的方法:
import org.apache.commons.codec.binary.Hex;
public static String bytesToHex(byte[] bytes) {
return Hex.encodeHexString(bytes);
}
方法4:手动实现(不推荐,但有助于理解)
public static String bytesToHex(byte[] bytes) {
char[] hexArray = "0123456789abcdef".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
使用示例
public static void main(String[] args) {
byte[] bytes = { (byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78, (byte)0x9A, (byte)0xBC, (byte)0xDE, (byte)0xF0 };
// 方法1
System.out.println("单个byte: " + byteToHex(bytes[0])); // 输出: 12
// 方法2
System.out.println("byte数组: " + bytesToHex(bytes)); // 输出: 123456789abcdef0
// 方法3(需要引入commons-codec库)
// System.out.println("使用Apache Commons: " + Hex.encodeHexString(bytes));
}
大小写控制
如果需要大写输出,只需修改格式字符串:
// 小写
String.format("%02x", b)
// 大写
String.format("%02X", b)
方法中,推荐使用String.format()方法或Apache Commons Codec库,因为它们既简洁又高效。
