- Write a java program to convert a decimal number to hexadecimal number.
- Java program to convert base 10 to base 16 number system.
In this java program, we will first take a decimal number from user and then convert it to hexadecimal number. Here, we will learn about fundamentals of decimal and hexadecimal number system and how to convert decimal numbers to hexadecimal numbers. Before jumping into java program, here is the brief introduction of decimal and hexadecimal number systems.
- Hexadecimal number system is base 16 number system and using digits from 0 to 9 and A to F.
- Decimal number system is a base 10 number system using digits 0 and 9.
1000 in Decimal is equivalent to 38E in Hexadecimal number system.
Java program to convert decimal number to hexadecimal number
package com.tcc.java.programs; import java.util.Scanner; /** * Java Program to */ public class DecimalToHex { public static void main(String[] args) { int dec; Scanner scanner; scanner = new Scanner(System.in); System.out.println("Enter a Decimal Number"); dec = scanner.nextInt(); // Calling decimalToBinary method to convert decimal // number to binary decimalToHex(dec); } /** * Method to convert a decimal number to hexadecimal number */ public static void decimalToHex(int dec) { char hexDigits[] = "0123456789ABCDEF".toCharArray(); String hex = ""; int i, remaindar; /* Convert Decimal Number to Hexadecimal Numbers */ while (dec != 0) { remaindar = dec % 16; hex = hex + hexDigits[remaindar]; dec /= 16; } System.out.print("HexaDecimal Number : "); // Print hex array in reverse order for (i = hex.length() - 1; i >= 0; i--) { System.out.print(hex.charAt(i)); } } }Output
Enter a Decimal Number 500 HexaDecimal Number : 1F4
Enter a Decimal Number 20 HexaDecimal Number : 14