繁体   English   中英

将十六进制转换为字符串

[英]Convert Hexadecimal to String

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

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

这在顶部投票的答案中概述: 在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);
}

另一种方法是使用来自javax.xml.bind包的DatatypeConverter

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM