Convert Decimal to Hexadecimal in Java

There are two ways to convert Decimal to Hexadecimal in Java:

  • Using the toHexString() method
  •  With a custom logic

Convert Decimal to Hexadecimal in Java using the toHexString() method

The easiest way is to use the ToHexString() static method of the Integer class to get the Hexadecimal String of a Decimal number.

Example

class Test {

  public static void main(String[] args) {

    System.out.println(Integer.toHexString(12));
    System.out.println(Integer.toHexString(29));
    System.out.println(Integer.toHexString(302));
  }
}
Output: c 1d 12e

Convert Decimal to Hexadecimal in Java with custom logic

We can implement our custom logic to convert Decimal to Hexadecimal like in the following program:

public class Test {

  public static void main(String[] args) {

    System.out.println(toHex(12));
    System.out.println(toHex(29));
    System.out.println(toHex(302));
  }

  public static String toHex(int number) {
    char hexchars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    String hexString = "";
    int rem;

    while (number > 0) {
      rem = number % 16;
      hexString = hexchars[rem] + hexString;
      number = number / 16;
    }

    return hexString;
  }
}
Output: C 1D 12E
 
This code creates a static Java method called “toHex” that uses a char array called “hexchars” to store the hexadecimal digits (0-9, A-F). A string called “hexString” is initialized as an empty string and will store the final hexadecimal representation. The method uses a while loop to repeatedly divide the input number by 16, and each remainder is used as an index to retrieve the corresponding hexadecimal digit from the “hexchars” array. The hexadecimal digit is then added to the “hexString” and the process repeats until the input number is less than or equal to zero. Finally, the method returns the hexadecimal representation of the input number as a string.
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *