How to convert hex string to Java string?

175,086

Solution 1

Using Hex in Apache Commons:

String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";    
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));

Solution 2

byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);

Solution 3

You can go from String (hex) to byte array to String as UTF-8(?). Make sure your hex string does not have leading spaces and stuff.

public static byte[] hexStringToByteArray(String hex) {
    int l = hex.length();
    byte[] data = new byte[l / 2];
    for (int i = 0; i < l; i += 2) {
        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                + Character.digit(hex.charAt(i + 1), 16));
    }
    return data;
}

Usage:

String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);

Solution 4

First of all read in the data, then convert it to byte array:

 byte b = Byte.parseByte(str, 16); 

and then use String constructor:

new String(byte[] bytes) 

or if the charset is not system default then:

new String(byte[] bytes, String charsetName) 

Solution 5

Try the following code:

public static byte[] decode(String hex){

        String[] list=hex.split("(?<=\\G.{2})");
        ByteBuffer buffer= ByteBuffer.allocate(list.length);
        System.out.println(list.length);
        for(String str: list)
            buffer.put(Byte.parseByte(str,16));

        return buffer.array();

}

To convert to String just create a new String with the byte[] returned by the decode method.

Share:
175,086
Qi Wang
Author by

Qi Wang

I am very poor when it comes to complex algorithms :) So plz try to make this things simpler to me

Updated on September 28, 2020

Comments

  • Qi Wang
    Qi Wang over 3 years

    For logging purpose we are converting the logs to byte array and then to hex string. I want to get it back in a Java String, but I am not able to do so.

    The hex string in log file looks something like

    fd00000aa8660b5b010006acdc0100000101000100010000
    

    How can I decode this?

  • Joker_vD
    Joker_vD over 11 years
    Of course, it may or may not work depending on encoding used by "some other guys". Maybe they used Latin-9. Or UTF-8. Or EUC-JP. Or maybe it was in Big-Endian. Who knows?
  • Aleksander Gralak
    Aleksander Gralak over 11 years
    That's why you should specify the encoding which was used by log strings before conversion to hex string.
  • gogognome
    gogognome over 11 years
    use Byte.parseByte(str, 16); to parse a hexadecimal number.
  • domenukk
    domenukk over 8 years
    I changed Byte.parseByte to (byte)Integer.parseInteger to allow for numbers > 128 to be parsed.
  • kodepet
    kodepet over 8 years
    The String constructor expects a byte array and not just byte, I tried and it failed.
  • Aleksander Gralak
    Aleksander Gralak over 8 years
    @Callforeach yes it it exactly what I gave as en example, byte[] stands for array not single byte: new String(byte[] bytes)
  • Jonathan
    Jonathan over 7 years
    Lots of substrings being created. Not ideal.
  • Error
    Error over 7 years
    @domenukk it's Integer.parseInt(..) not Integer.parseInteger(..) . Byte.parseByte implemented as follow { return (byte) Integer.parseInt(Str, base);}
  • Error
    Error over 7 years
    @Munene thanx 4 regex
  • Kaveesh Kanwal
    Kaveesh Kanwal over 7 years
    how to do ot for versions below kitkat?
  • zundi
    zundi almost 7 years
    Where the heck do I find DatatypeConverter?
  • zundi
    zundi almost 7 years
    I'm not following... where did you get the bytes byte array from?
  • Aleksander Gralak
    Aleksander Gralak almost 7 years
    @zundi in first line you parse only single byte. So you need to use a loop to get all the bytes and put them in array. Please look at Munene iUwej Julius answer. His method is doing just that
  • DwB
    DwB over 5 years
    Hex is now part of Apache Commons Codec
  • Jean-Alexis Aufauvre
    Jean-Alexis Aufauvre about 5 years
    Not public anymore in recent Java versions
  • Jacques Koorts
    Jacques Koorts almost 5 years
    Here the dependency: <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.12</version> </dependency>
  • Holger
    Holger over 4 years
    It doesn’t need much to recognize, that this data is not a UTF-8 encoded string and new String(bytes, "UTF-8") will just produce garbage.
  • Admin
    Admin over 4 years
    may I ask what is the purpose of converting it to String as UTF-8?
  • roninjoe
    roninjoe over 4 years
    replace "String str" with a StringBuffer(), and use sb.append(char) if performance is an issue.
  • telebog
    telebog over 4 years
    javax.xml.bind.DatatypeConverter
  • gumuruh
    gumuruh over 3 years
    what are the encoding values?
  • telebog
    telebog over 3 years