【问题标题】:Convert Hexadecimal to String将十六进制转换为字符串
【发布时间】:2015-12-24 17:11:08
【问题描述】:

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

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

这在此处获得最高票数的答案中进行了概述: Converting A String To Hexadecimal In Java

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

【问题讨论】:

标签: java string numbers hex


【解决方案1】:

您可以从转换后的字符串重构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)));
    }
}

注意:去除 fromHex 中的前导 00 只是因为 toHex 方法中的 "%040x" 填充是必要的。 如果您不介意用简单的%x 替换它, 那么你可以把这行放在fromHex:

    hex = hex.replaceAll("^(00)+", "");

【讨论】:

  • 效果很好...有没有使用 String.format/BigInteger(StringToHex 完成的方式)部分来执行此操作(Hex to String)?
  • 不是使用 String.format/BigInteger,而是使用 DatatypeConverter(更新答案)
【解决方案2】:
String hexString = toHex("abc");
System.out.println(hexString);
byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
System.out.println(new String(bytes, "UTF-8"));

输出:

0000000000000000000000000000000000616263
abc

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2018-01-22
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2014-12-25
    相关资源
    最近更新 更多