将十六进制转换为字符串

时间:2015-09-27 09:25:36

标签: java string numbers hex

要将String转换为Hexadecimal,我正在使用:

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

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

我该怎么做反向,即十六进制到字符串?

2 个答案:

答案 0 :(得分:2)

您可以从转换后的字符串重建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)+", "");

答案 1 :(得分:0)

String hexString = toHex("abc");
System.out.println(hexString);
byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
System.out.println(new String(bytes, "UTF-8"));

输出:

0000000000000000000000000000000000616263
abc