Main Tutorials

How to convert String to Hex in Java

Here are a few Java examples of converting between String or ASCII to and from Hexadecimal.

  • Apache Commons Codec – Hex
  • Integer
  • Bitwise

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

1. Apache Commons Codec

Both Hex.encodeHex and Hex.decodeHex can convert String to Hex and vice versa.

pom.xml

  <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.14</version>
  </dependency>
HexUtils.java

package com.mkyong;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;

public class HexUtils {

    public static void main(String[] args) {

        String input = "a";
        System.out.println("input : " + input);

        String hex = convertStringToHex(input);
        System.out.println("hex : " + hex);

        String result = convertHexToString(hex);
        System.out.println("result : " + result);

    }

    public static String convertStringToHex(String str) {

        // display in uppercase
        //char[] chars = Hex.encodeHex(str.getBytes(StandardCharsets.UTF_8), false);

        // display in lowercase, default
        char[] chars = Hex.encodeHex(str.getBytes(StandardCharsets.UTF_8));

        return String.valueOf(chars);
    }

    public static String convertHexToString(String hex) {

        String result = "";
        try {
            byte[] bytes = Hex.decodeHex(hex);
            result = new String(bytes, StandardCharsets.UTF_8);
        } catch (DecoderException e) {
            throw new IllegalArgumentException("Invalid Hex format!");
        }
        return result;
    }
}

Output


input : a
hex : 61
result : a

2. Integer

This example is easy to understand, use JDK Integer APIs like Integer.toHexString and Integer.parseInt(hex, 16) to convert the String to Hex and vice versa.

The idea is convert String <==> Decimal <==> Hex, for example char a, decimal is 97, hex is 61.

HexUtils2.java

package com.mkyong;

public class HexUtils2 {

    public static void main(String[] args) {

        String input = "a";
        System.out.println("input : " + input);

        String hex = convertStringToHex(input);
        System.out.println("hex : " + hex);

        String result = convertHexToString(hex);
        System.out.println("result : " + result);

    }

    // Char -> Decimal -> Hex
    public static String convertStringToHex(String str) {

        StringBuffer hex = new StringBuffer();

        // loop chars one by one
        for (char temp : str.toCharArray()) {

            // convert char to int, for char `a` decimal 97
            int decimal = (int) temp;

            // convert int to hex, for decimal 97 hex 61
            hex.append(Integer.toHexString(decimal));
        }

        return hex.toString();

    }

    // Hex -> Decimal -> Char
    public static String convertHexToString(String hex) {

        StringBuilder result = new StringBuilder();

        // split into two chars per loop, hex, 0A, 0B, 0C...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            String tempInHex = hex.substring(i, (i + 2));

            //convert hex to decimal
            int decimal = Integer.parseInt(tempInHex, 16);

            // convert the decimal to char
            result.append((char) decimal);

        }

        return result.toString();

    }

}

Output


input : a
hex : 61
result : a

For input java


input : java
hex : 6a617661
result : java

3. Bitwise

This bitwise conversion is similar to the Apache Commons Codec source code, read comment for self-explanatory.

HexUtils3.java

package com.mkyong;

import java.nio.charset.StandardCharsets;

public class HexUtils3 {

    private static final char[] HEX_UPPER = "0123456789ABCDEF".toCharArray();
    private static final char[] HEX_LOWER = "0123456789abcdef".toCharArray();

    public static void main(String[] args) {

        String input = "java";
        System.out.println("input : " + input);

        String hex = convertStringToHex(input, false);
        System.out.println("hex : " + hex);

    }

    public static String convertStringToHex(String str, boolean lowercase) {

        char[] HEX_ARRAY = lowercase ? HEX_LOWER : HEX_UPPER;

        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);

        // two chars form the hex value.
        char[] hex = new char[bytes.length * 2];

        for (int j = 0; j < bytes.length; j++) {

            // 1 byte = 8 bits,
            // upper 4 bits is the first half of hex
            // lower 4 bits is the second half of hex
            // combine both and we will get the hex value, 0A, 0B, 0C

            int v = bytes[j] & 0xFF;               // byte widened to int, need mask 0xff
                                                   // prevent sign extension for negative number

            hex[j * 2] = HEX_ARRAY[v >>> 4];       // get upper 4 bits

            hex[j * 2 + 1] = HEX_ARRAY[v & 0x0F];  // get lower 4 bits

        }

        return new String(hex);

    }

}

Output


input : java
hex : 6A617661

Note
If you are confused, picks Apache Commons Codec for the safe bet.

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
18 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Arun
10 years ago

But this creates a problem for a hex string with value between 80 to 9F.

I am doing byte dump of the ASCII and am seeing if it has the same hexa value. For values between 80 to 9F, doesnt happen so.

Any ideas.?

Wellington
4 years ago
Reply to  Arun

Hi friend. How are you?
did you figure it out?
I am trying to solve this problem for days.

I will be very grateful for a return. hug

Sriram
4 years ago
Reply to  Wellington

i have a solution for this problem. Except for a few decimals 129, 141, 143, 144, 157 im able to get the ascii values of them all. Let me know if u need the program.

david
5 years ago

so good.

Jose
9 years ago

Hello ,
I can not convert from hexadecimal to 255 caracters ascii table .
Sera you could help me ???
An example is
80 == O , y = 79 .
is going to see a net 255 ascii character table .
I await response !!
Thank you !!!

Sriram
4 years ago
Reply to  Jose

i have a solution for this problem. Except for a few decimals 129, 141, 143, 144, 157 im able to get the ascii values of them all. Let me know if u need the program.

khalid
11 years ago

So nice

Gaius
11 years ago

Hi Mkyoung,
thank you so much for the tutorials you keep providing. It is of great help to a lot of people and we are greatful for the time and effort you put into all these.Please i was wondering if you can assist with Encryption steps code or tutorial. I am writing a project that should spell out all the setps involved in DES encryption from input through the Initial Permutaion, the 16 Rounds involved, down to the final output. But to show all details in all the steps. Would you have any advice or guidance, tutorial or code to that regard? most of the tips online always go straight to encrypt and decrypt but there is really no much on the individual steps. Any help will be greatly appreciated. Thanks in advace

Gaius

preechaw
11 years ago

I think the method convertStringToHex may need a little modification.
It doesn’t handle hex below 0x10.
For example, if the argument is “I\tlove Java!”, the second byte will become just “9” instead of “09”.

public String convertStringToHex(String str){

char[] chars = str.toCharArray();

StringBuffer hex = new StringBuffer();
int each;
for(int i = 0; i < chars.length; i++){
each = (int)chars[i];
if (each < 0x10) // in this case, ASCII code is 1 digit hex
{
hex.append("0");
}
hex.append(Integer.toHexString(each));
}

return hex.toString();
}

Techbrainless
12 years ago

Thanks mkyong , It is really amazing post.

your website is one of my top 10 java references sites
Keep it up….:)

Himanshu
12 years ago

superb code, thanks.

Lu
12 years ago

Works fine even with extended ASCII (èéòà..). It saves me 15 minutes to write it on my own 🙂

Stanislav
13 years ago

Thank you for Hex to String function. It save my day!

Guy Mac
14 years ago

Don’t re-invent the wheel, just use String.format.

Desh
8 years ago
Reply to  mkyong

public String StringToHex(String arg) {
return String.format(“%040x”, new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
Not sure about HexToString…