Convert String to Hex in Java

Rupam Yadav Jan 30, 2023 May 31, 2021
  1. Convert String to Hex by Using Array of char and Integer.toHexString()
  2. Convert String to Hex Using Array of byte and String Formatter
  3. Convert String to Hex Using Apache Commons Codec
Convert String to Hex in Java

In this article, we’ll learn how to convert a string to a hexadecimal value using four ways that are shown below with examples.

Convert String to Hex by Using Array of char and Integer.toHexString()

The first technique uses the conversion of the string to an array of char. We first create an object of StringBuilder() that we use to append the characters to create the whole string of hex values. To convert the string to a char array, we use the toCharArray() command. After that, we use an enhanced loop and the Integer.toHexString() method, which accepts a single char as an argument.

The function, Integer.toHexString(), converts the char to hexadecimal, and then we use the stringBuilder.append() method to append the strings and show it to the output.

public class StringToHex {
    public static void main(String[] args) {

        String stringToConvert = "This is a string";

        convertStringToHex(stringToConvert);
    }

    private static void convertStringToHex(String str) {
        StringBuilder stringBuilder = new StringBuilder();

        char[] charArray = str.toCharArray();

        for (char c : charArray) {
            String charToHex = Integer.toHexString(c);
            stringBuilder.append(charToHex);
        }

        System.out.println("Converted Hex from String: "+stringBuilder.toString());
    }
}

Output:

Converted Hex from String: 54686973206973206120737472696e67

Convert String to Hex Using Array of byte and String Formatter

In this example, we first convert the string to an array of bytes getBytesFromString using the getBytes() function. We have to pass the charset inside the getBytes() method as an argument. Once we get the byte array, we create an object of BigInteger, and in the constructor, we pass an int value 1 and the byte array as arguments.

We use the String.format() method to format the bigInteger object values into a hex string. Once we get the hex string, we print it.

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

public class StringToHex {
    public static void main(String[] args) {

        String stringToConvert = "We have to convert this string to hex";

        convertStringToHex(stringToConvert);
    }

    private static void convertStringToHex(String str) {

        byte[] getBytesFromString = str.getBytes(StandardCharsets.UTF_8);
        BigInteger bigInteger = new BigInteger(1, getBytesFromString);

        String convertedResult = String.format("%x", bigInteger);

        System.out.println("Converted Hex from String: " + convertedResult);
    }
}

Output:

Converted Hex from String: 5765206861766520746f20636f6e76657274207468697320737472696e6720746f20686578

Convert String to Hex Using Apache Commons Codec

In the last method of converting a string to hex Java, we use the Apache Commons Codec library. To include the library in our project, we’ll use the following maven dependency:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

Like the last example, we will get an array of byte from the string that we want to convert in this program. Then we use the Hex class of the Apache Commons-Codec library and call its static method encodeHexString() and pass the byteArray as its argument. We then get the string in return that is converted into hex.

We can use the function encodeHex() instead of encodeHexString(), but it will return a char array that we have to convert to a string; however, the result will be the same.

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

import java.nio.charset.StandardCharsets;

public class StringToHex {
    public static void main(String[] args) {

        String stringToConvert = "We have to convert this string to hex";

        convertStringToHex(stringToConvert);
    }

    private static void convertStringToHex(String str) {

        byte[] byteArray = str.getBytes(StandardCharsets.UTF_8);
        String convertedResult = Hex.encodeHexString(byteArray);

        System.out.println("Converted Hex from String: " + convertedResult);
    }
}

Output:

Converted Hex from String: 5765206861766520746f20636f6e76657274207468697320737472696e6720746f20686578
Author: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

Related Article - Java String

Related Article - Java Hex