您可以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)));
}
}
注:领先剥离00
的fromHex
仅仅是必要的,因为的"%040x"
你的填充toHex
方法。如果您不介意将其替换为简单的%x
,则可以将此行放在fromHex
:
hex = hex.replaceAll("^(00)+", "");