转换十六进制转换为字符串
问题描述:
至字符串转换为十六进制我使用:转换十六进制转换为字符串
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)));
}
}
注意:由于您的toHex
方法中有"%040x"
填充,因此仅在fromHex
中删除前导00
。 如果你不介意更换一块简单%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
答
如果你是试图解析编码为十六进制文字的整数时,可以使用Integer.parseInt
/Long.parseLong
,基数为16.这里有一个例子:
System.out.println(Long.parseLong("BAADF00D", 16));
// 3131961357
http://*.com/questions/13990941/how-to-convert-hex-string-to-java-string – jjlema