将十六进制转换为字符串
Convert Hexadecimal to String
要将字符串转换为十六进制,我正在使用:
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes("UTF-8")));
}
这在此处的最高投票答案中有所概述:
Converting A String To Hexadecimal In Java
我如何做相反的操作,即将十六进制转换为字符串?
您可以从转换后的字符串中重建 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);
}
另一种方法是使用 DatatypeConverter
,来自 javax.xml.bind
包:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = DatatypeConverter.parseHexBinary(hex);
return new String(bytes, "UTF-8");
}
要验证的单元测试:
@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)));
}
}
注意:在 fromHex
中去除前导 00
只是因为 toHex
方法中的 "%040x"
填充是必要的。
如果您不介意用简单的 %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"));
输出:
0000000000000000000000000000000000616263
abc
要将字符串转换为十六进制,我正在使用:
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes("UTF-8")));
}
这在此处的最高投票答案中有所概述: Converting A String To Hexadecimal In Java
我如何做相反的操作,即将十六进制转换为字符串?
您可以从转换后的字符串中重建 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);
}
另一种方法是使用 DatatypeConverter
,来自 javax.xml.bind
包:
public String fromHex(String hex) throws UnsupportedEncodingException {
hex = hex.replaceAll("^(00)+", "");
byte[] bytes = DatatypeConverter.parseHexBinary(hex);
return new String(bytes, "UTF-8");
}
要验证的单元测试:
@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)));
}
}
注意:在 fromHex
中去除前导 00
只是因为 toHex
方法中的 "%040x"
填充是必要的。
如果您不介意用简单的 %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"));
输出:
0000000000000000000000000000000000616263
abc