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() 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
 
That’s it!

Leave a Reply

Your email address will not be published.