-
简洁写法
代码如下,代码量很小
/**
* 简洁写法 16进制字符串转成byte数组
* @param hex 16进制字符串,支持大小写
* @return byte数组
*/
public static byte[] hexStringToBytes(String hex) {
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return bytes;
}
/**
* 简洁写法 byte数组转成16进制字符串
* @param bytes byte数组
* @return 16进制字符串
*/
public static String bytesToHexString(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
builder.append(String.format("%02X", b));
}
return builder.toString();
}
-
高效写法
代码如下,代码量略多,但运行效率要高很多
/**
* 高效写法 16进制字符串转成byte数组
*
* @param hex 16进制字符串,支持大小写
* @return byte数组
*/
public static byte[] hexStringToBytes(String hex) {
byte[] result = new byte[hex.length() / 2];
char[] chars = hex.toCharArray();
for (int i = 0, j = 0; i < result.length; i++) {
result[i] = (byte) (toByte(chars[j++]) << 4 | toByte(chars[j++]));
}
return result;
}
private static int toByte(char c) {
if (c >= '0' && c <= '9') return (c - '0');
if (c >= 'A' && c <= 'F') return (c - 'A' + 0x0A);
if (c >= 'a' && c <= 'f') return (c - 'a' + 0x0a);
throw new RuntimeException("invalid hex char '" + c + "'");
}
/**
* 高效写法 byte数组转成16进制字符串
*
* @param bytes byte数组
* @return 16进制字符串
*/
public static String bytesToHexString(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int c = 0;
for (byte b : bytes) {
buf[c++] = digits[(b >> 4) & 0x0F];
buf[c++] = digits[b & 0x0F];
}
return new String(buf);
}
private final static char[] digits = "0123456789ABCDEF".toCharArray();