Convert hexadecimal to string

To convert String to hex, I use:

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

This is stated in the main vote: Converting a string to hexadecimal in Java

How to do the opposite ie hexadecimal in String?

+4
source share
3 answers

You can restore bytes[]from a converted string, here is one way to do this:

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 to use DatatypeConverter, from the package 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");
}

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

: 00 fromHex - "%040x" toHex. %x, fromHex:

    hex = hex.replaceAll("^(00)+", "");
+2
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

0

Source: https://habr.com/ru/post/1609165/


All Articles