[英]Convert Hexadecimal to String
To convert String to Hexadecimal i am using: 要将String转换为十六进制,我正在使用:
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes("UTF-8")));
}
This is outlined in the top-voted answer here: Converting A String To Hexadecimal In Java 这在顶部投票的答案中概述: 在Java中将字符串转换为十六进制
How do i do the reverse ie Hexadecimal to String? 我如何反向,即十六进制到字符串?
You can reconstruct bytes[]
from the converted string, here's one way to do it: 您可以从转换后的字符串重建
bytes[]
,这是一种方法:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2) {
bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
}
return new String(bytes);
}
Another way is using DatatypeConverter
, from javax.xml.bind
package: 另一种方法是使用来自
javax.xml.bind
包的DatatypeConverter
:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = DatatypeConverter.parseHexBinary(hex);
return new String(bytes, "UTF-8");
}
Unit tests to verify: 单元测试验证:
@Test
public void test() throws UnsupportedEncodingException {
String[] samples = {
"hello",
"all your base now belongs to us, welcome our machine overlords"
};
for (String sample : samples) {
assertEquals(sample, fromHex(toHex(sample)));
}
}
Note: the stripping of leading 00
in fromHex
is only necessary because of the "%040x"
padding in your toHex
method. 注意:由于
toHex
方法中的"%040x"
填充,仅需要从fromHex
去除前导00
。 If you don't mind replacing that with a simple %x
, then you could drop this line in fromHex
: 如果您不介意用简单的
%x
替换它,那么您可以将此行放在fromHex
:
hex = hex.replaceAll("^(00)+", "");
String hexString = toHex("abc");
System.out.println(hexString);
byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
System.out.println(new String(bytes, "UTF-8"));
output: 输出:
0000000000000000000000000000000000616263
abc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.