4

To convert String to Hexadecimal i am using:

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

This is outlined in the top-voted answer here: Converting A String To Hexadecimal In Java

How do i do the reverse i.e Hexadecimal to String?

Salman A
  • 248,760
  • 80
  • 417
  • 510
Jasper
  • 7,942
  • 27
  • 90
  • 131

2 Answers2

3

You can reconstruct bytes[] from the converted string, here's one way to do it:

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

Another way is using DatatypeConverter, from javax.xml.bind package:

public String fromHex(String hex) throws UnsupportedEncodingException {
    hex = hex.replaceAll("^(00)+", "");
    byte[] bytes = DatatypeConverter.parseHexBinary(hex);
    return new String(bytes, "UTF-8");
}

Unit tests to verify:

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

Note: the stripping of leading 00 in fromHex is only necessary because of the "%040x" padding in your toHex method. If you don't mind replacing that with a simple %x, then you could drop this line in fromHex:

    hex = hex.replaceAll("^(00)+", "");
janos
  • 115,756
  • 24
  • 210
  • 226
  • That works perfectly...is there anyway to do this (Hex to String) using String.format/BigInteger (the way it is done for StringToHex) part? – Jasper Sep 27 '15 at 17:51
  • Not with String.format/BigInteger, but using DatatypeConverter (updated answer) – janos Sep 28 '15 at 05:54
1
String hexString = toHex("abc");
System.out.println(hexString);
byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
System.out.println(new String(bytes, "UTF-8"));

output:

0000000000000000000000000000000000616263
abc
Hong Duan
  • 3,954
  • 2
  • 26
  • 49