将十六进制转换为字符串

Jas*_*per 5 java string hex numbers

要将字符串转换为十六进制,我正在使用:

public String toHex(String arg) {
    return String.format("%040x", new BigInteger(1, arg.getBytes("UTF-8")));
}
Run Code Online (Sandbox Code Playgroud)

这在投票最高的答案中进行了概述: Converting A String To Hexadecimal In Java

我该如何做相反的事情,即十六进制到字符串?

Sto*_*ica 4

您可以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);
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用包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");
}
Run Code Online (Sandbox Code Playgroud)

单元测试来验证:

@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)));
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:仅由于方法中的填充,才需要剥离00引入。如果您不介意将其替换为简单的,那么您可以将此行放入:fromHex"%040x"toHex%xfromHex

    hex = hex.replaceAll("^(00)+", "");
Run Code Online (Sandbox Code Playgroud)