Java中16进制字符串转byte数组
在Java中,将16进制字符串转换为byte数组是一个常见的需求,以下是几种实现方法:

方法1:使用BigInteger(推荐)
public static byte[] hexToByteArray(String hex) {
if (hex == null || hex.length() % 2 != 0) {
throw new IllegalArgumentException("Invalid hex string");
}
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i+1), 16));
}
return data;
}
方法2:使用Apache Commons Codec
如果你使用Apache Commons库,可以更简单地实现:
import org.apache.commons.codec.binary.Hex;
public static byte[] hexToByteArray(String hex) {
return Hex.decodeHex(hex.toCharArray());
}
方法3:使用Java 8的Stream API
import java.util.stream.IntStream;
public static byte[] hexToByteArray(String hex) {
if (hex == null || hex.length() % 2 != 0) {
throw new IllegalArgumentException("Invalid hex string");
}
byte[] bytes = new byte[hex.length() / 2];
IntStream.range(0, bytes.length)
.forEach(i -> bytes[i] = (byte) Integer.parseInt(
hex.substring(2 * i, 2 * i + 2), 16));
return bytes;
}
方法4:使用位运算
public static byte[] hexToByteArray(String hex) {
int len = hex.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i+1), 16));
}
return data;
}
使用示例
public static void main(String[] args) {
String hexString = "1a2b3c4d5e6f";
byte[] byteArray = hexToByteArray(hexString);
// 打印结果
for (byte b : byteArray) {
System.out.printf("%02X ", b);
}
}
注意事项
- 输入的16进制字符串长度必须是偶数,否则无法正确转换
- 不区分大小写,可以处理"1A2B"或"1a2b"这样的输入
- 如果字符串包含非16进制字符,会抛出IllegalArgumentException
- 转换后的byte数组中的值可能是负数(因为byte是有符号的),这是正常现象
方法都能实现16进制字符串到byte数组的转换,选择哪种取决于你的具体需求和项目环境。

