2015-09-27 141 views

回答

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))); 
    } 
} 

注意:由于您的toHex方法中有"%040x"填充,因此仅在fromHex中删除前导00。 如果你不介意更换一块简单%x, 那么你可以删除该行fromHex

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

完美的作品...是无论如何,要做到这一点(十六进制字符串)使用String.format/BigInteger(它为StringToHex完成的方式)的一部分? – Jasper

+0

不适用于String.format/BigInteger,但使用DatatypeConverter(已更新的答案) – janos

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

输出:

0000000000000000000000000000000000616263 
abc 
0

如果你是试图解析编码为十六进制文字的整数时,可以使用Integer.parseInt/Long.parseLong,基数为16.这里有一个例子:

System.out.println(Long.parseLong("BAADF00D", 16)); 
// 3131961357 

Demo on Ideone

相关问题