这是将字符串十六进制转换为字节的最佳方式吗? [英] Is this the best way to convert String hex to bytes?
本文介绍了这是将字符串十六进制转换为字节的最佳方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是将字符串十六进制转换为字节的最佳方式吗?
或者你认为更简单吗?
Is this the best way to convert String hex to bytes? Or can you think a shorter/simpler?
public static byte[] hexToBytes(String hex) {
return hexToBytes(hex.toCharArray());
}
public static byte[] hexToBytes(char[] hex) {
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[i * 2], 16);
int low = Character.digit(hex[i * 2 + 1], 16);
int value = (high << 4) | low;
if (value > 127)
value -= 256;
raw[i] = (byte) value;
}
return raw;
}
推荐答案
byte[] yourBytes = new BigInteger(hexString, 16).toByteArray();
这篇关于这是将字符串十六进制转换为字节的最佳方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文