How do I convert decimal to hexadecimal?

To convert decimal number (base 10) to hexadecimal number (base 16) we can use the Integer.toHexString() method. This method takes an integer as parameter and return a string that represent the number in hexadecimal.

To convert back the number from hexadecimal to decimal number we can use the Integer.parseInt() method. This method takes two argument, the number to be converted, which is the string that represent a hexadecimal number. The second argument is the radix, we pass 16 which tell the method if the string is a hexadecimal number.

package org.kodejava.lang;

public class ToHexadecimalExample {
    public static void main(String[] args) {
        // Converting a decimal value to its hexadecimal representation 
        // can be done using Integer.toHexString() method.
        System.out.println(Integer.toHexString(1976));

        // On the other hand to convert hexadecimal string to decimal
        // we can use Integer.parseInt(string, radix) method, 
        // where radix for hexadecimal is 16.
        System.out.println(Integer.parseInt("7b8", 16));
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.