Java Decimal to Hexadecimal Conversion

In Mathematics, we use various positional numbering schemes for representing numbers. We are familiar with decimal numbering system which uses a base of 10. Two other commonly used numbering systems in computing are hexadecimal (base 16) and binary (base 2).

Conversion of decimal value to hex string requires the following steps,

  • Find the reminder of the decimal value when it is divided by 16.
  • Find the corresponding hex character to get the right most character of the hex result
  • Divide the decimal value by 16 and use it as the decimal value for the next iteration
  • Repeat the steps to get each character in the hex result

The following program uses the above algorithm to convert decimal value to its corresponding hexadecimal string,

/**
 * Converts a decimal number to a hexadecimal string 
 */
public class DecimalToHex {
    public static String HEX_CHARACTERS="0123456789ABCDEF";
    
    public static void main(String[] args) {
        DecimalToHex dh = new DecimalToHex();
        int decValue = 922;
        String hex = dh.dec2hex(decValue);
        System.out.println("Hexadecimal value of "+decValue+" is "+hex);
    }

    /**
     * 
     * @param decValue decimal value to be converted
     * @return hexadecimal string representation
     */
    private String dec2hex(int decValue) {
        if(decValue==0) return "0";
        String hexVal="";
        while(decValue > 0) {
            // find right most digit in hex
			int digit = decValue%16;
            hexVal = HEX_CHARACTERS.charAt(digit)+hexVal;
			
			decValue = decValue/16;
        }
        return hexVal;
    }
}