Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn how to convert an integer value to hexadecimal in Java. We’ll discuss the different methods available using code examples.

2. Convert Integer to Hexadecimal in Java

Before jumping into some code examples, let’s learn how integer to hexadecimal conversion works.

Integer numbers use a decimal base(10), i.e., numbers from 0 to 9. However, hexadecimal values are represented by only 16 symbols, 0 to 9 and A to F.

There are different ways to convert an integer value into a hexadecimal in Java. We can use a mathematical-based approach, some Java built-in functionalities, or third-party libraries. We’ll see each one of them in the following sections.

3. Raw Method

First, we’ll start using a simple mathematical algorithm to convert our input integer data:

  1. Divide the integer by 16
  2. Divide the result of the division by 16
  3. Take the remainder of the division and convert it to a hexadecimal digit
  4. Repeat steps one and two until the result of the division is 0

Let’s build up our custom converter class based on the above algorithm:

class IntegerToHex {
    static final String digits = "0123456789ABCDEF";
    static String integerToHex(int input) {
        if (input <= 0)
            return "0";
        StringBuilder hex = new StringBuilder();
        while (input > 0) {
            int digit = input % 16;
            hex.insert(0, digits.charAt(digit));
            input = input / 16;
        }
        return hex.toString();
    }
}

The above code uses the described algorithm to get the hex value from the input integer.

Next, let’s test our method:

@Test
void givenIntegerValue_whenUseRawMethod_thenWillGetHexValue() {
    String result = IntegerToHex.integerToHex(1055);
    assertEquals("41F", result);
}

The drawback of our implementation is that it only accepts positive integers greater than zero.

4. String format() Method

The next method comes from the String class, the format() method. In this case, we use the %x specifier to get the hex format output. Let’s test this behavior:

@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValue() {
    String result = String.format("%02x", 255);
    assertEquals("ff", result);
}

The format() method formats 255 as a two-digit hexadecimal number in our code example.

We can change the number of left padding zeros in the resulting hexadecimal by changing the number in the specifier. Let’s replace %02x with the %04x specifier in our next test:

@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZeros() {
    String result = String.format("%04x", 255);
    assertEquals("00ff", result);
}

We can notice from our previous test case that the expected result changed from the initial “ff” to “00ff” when the specifier changed to %04x.

If we need the result hex value in upper case, we only need to change “x” by “X” in the format specifier:

@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZerosAndUpperLetter() {
    String result = String.format("%04X", 255);
    assertEquals("00FF", result);
}

5. Using toHexString() Method

Our next option is using toHexString(), present in both Integer and Long classes.

The static toHexString() method under the hood calls the toUnsignedString() method. In both cases, it converts the input value to an unsigned value. That’s why we need to avoid passing negative values to this method.

Let’s code some test cases to illustrate both uses. The first test case uses the toHexString() from the Integer class:

@Test
void givenIntegerValue_whenUseIntegerToHexString_thenWillGetHexValue() {
    String result = Integer.toHexString(1000);
    assertEquals("3e8", result);
}

Our next test is for the toHexString() method from the Long class:

@Test
void givenIntegerValue_whenUseLongToHexString_thenWillGetHexValue() {
    String result = Long.toHexString(255L);
    assertEquals("ff", result);
}

In the case of the first test, the input data for the toHexString() method was an Integer value. In the second test, the input data we passed as an argument to the method was a Long value.

6. Using toString() Method

In addition to the toHexString() method in the Integer and Long classes, we have the toString() method. This method takes two arguments and returns a string representing the first parameter using the radix defined by the second argument. For our case, the radix is 16 because we need the hex representation.

Let’s use the toString() method in the Integer class:

@Test
public void givenNegativeIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
    String result = Integer.toString(-1458, 16);
    assertEquals("-5b2", result);
}

In the above test case, we pass a negative integer with radix 16 to the toString() method. The result is a negative hex value. In contrast to earlier approaches, in which the data being input was only positive integers, the toString() method converts signed integers into signed hex values.

Our second test is similar to the first one, but we’ll use the toString() method in the Long class:

@Test
public void givenLongValue_whenUseLongToString_thenWillGetHexValue() {
    String result = Long.toString(158, 16);
    assertEquals("9e", result);
}

In this case, the toString() method works like the toString() method with the Integer class but with a long value as input data.

7. Apache Commons Codec Library

Finally, another way to get a hex value is using a third party-library like Apache Commons Codec. From Apache Commons Codec, we use the Hex class and the static method  encodeHexString()

We need to add the Apache Commons Codec dependency to our pom.xml file:

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

Now, we’re ready to implement our test case:

@Test
public void givenIntegerValue_whenUseApacheCommons_thenWillGetHexSignedValue() {
    String result = Hex.encodeHexString(new byte[] { (byte) 254 });
    assertEquals("fe", result);
}

In the above test, we passed a byte array as an argument – an array with only one element. We cast the integer input value to the byte data type.

This is the main drawback of this approach because the byte data type in Java is an 8-bit signed two’s complement integer, with values ranging from -128 to 127. For values of less than 255, we can use this approach without any problem.

Similar behavior to this is used by java.util.HexFormat. This feature was introduced in Java 17. The HexFormat class provides a simple and convenient way to convert between byte arrays and their corresponding hexadecimal string representations.

8. Conclusion

In this article, we implemented code examples using different ways to convert integer values into hexadecimal. With a deeper understanding of the code and best practices, we can efficiently execute the conversion and optimize the performance of our code. In our tests, we used both built-in methods and libraries in Java.

As always, all code snippets used in this article are available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.