这是将字符串十六进制转换为字节的最佳方法吗?
这是将字符串十六进制转换为字节的最佳方法吗? 或者你能想到更短/更简单的吗?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当值大于 127 时,不需要减去 256。只需将值转换为字节即可。例如,
byte b = (byte) 255
将值 -1 分配给b
。整数类型的缩小转换只是丢弃不适合目标类型的高位。
You don't need the subtraction of 256 when the value is greater than 127. Just cast the value to a byte. For example,
byte b = (byte) 255
assigns a value of -1 tob
.A narrowing conversion on integer types simply discards the high-order bits that don't fit in the target type.
不幸的是,当存在前导零字节时,使用 BigInteger 会失败。
我认为你最初的方法是一个好的开始。我做了一些调整:
请注意,
Character.digit
仅在 Java 7 中可用,并且它不会验证提供的字符是否在预期范围内。当输入数据与我的期望不符时,我喜欢抛出异常,所以我添加了它。以下是一些基本的单元测试:
Unfortunately, using
BigInteger
fails when there are leading zero bytes.I think your original approach is a good start. I made some tweaks:
Note that
Character.digit
is only available in Java 7, and it doesn't validate that the provided character is within the expected range. I like to throw exceptions when input data doesn't match my expectations, so I've added that.Here are some basic unit tests:
您可以使用 Bouncy Castle Crypto 包 - Java 和密码算法的 C# 实现。
Hex 类 Java 文档
源代码
maven 依赖
You can use the Bouncy Castle Crypto package - Java & C# implementation of cryptographic algorithms.
Hex class Java doc
source code
maven dependency
最简单的方法:
The easiest way: