ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to convert Decimal number to Hexadecimal number in Java ?.

Updated on September 17, 2014

Introduction

In this tutorial, you will learn how to convert a decimal number to hexadecimal number in Java. In number system a decimal number has a base of 10. It has digits from 0 to 9. A hexadecimal number in number system has a base of 16. It has a digits from 0 to 9 and A to F. Comparison between a decimal number and a hexadecimal number is shown in below table. In order to convert a decimal number to hexadecimal number, you have to perform below steps as -

Step 1 - Divide the decimal number by 16. It results in two important values. One is the remainder and other is quotient.

Step 2 - If remainder is less than 9, take it as a digit between 0 to 9. If remainder is between 10 to 15 than take 10 as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F. This remainder is the least significant digit for us.

Step 3 - Perform step 1 again with the quotient calculated in step 1. It again results in two important values. One is the remainder and other is quotient.

Step 4 - Perform step 2 as usual.

Step 5 - Perform all above steps till quotient comes out to be zero.

Step 6 - Hexadecimal number is remainder evaluated in reverse direction.


Lets take an example - say you want to convert decimal number 453 to hexadecimal.

Step 1 - Divide 453 by 16. It results in two values as : remainder = 5 and quotient = 28.

Step 2 - As remainder is 5 which is less than 9. Take least significant digit as 5.

Step 3 - Divide 28 by 16. It results in two values as : remainder = 12 and quotient = 1.

Step 4 - As remainder is between 10 to 15, therefore second last significant digit is C.

Step 5 - Divide 1 by 16. It results in two values as : remainder = 1 and quotient = 0.

Step 6 - As quotient is 0 division process stops and remainder is 1. Therefore, hexadecimal number is remainder evaluated in reverse direction. Here, remainder evaluation was 5 -> C -> 1. So, in our example hexadecimal of 453 is 1C5.


Table : Decimal Vs Hexadecimal

Decimal Number
Hexadecimal Number
0
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
A
11
B
12
C
13
D
14
E
15
F

Java video tutorial - How to convert Decimal number to Hexadecimal number in Java.

Java source code - How to convert Decimal number to Hexadecimal number in Java.

// Import necessary Java classes from Java API used in the tutorial. 
// Scanner class is in java.util package. It is been used here to take user
// inputs from console.
import java.util.Scanner;

// Create a Java class such as DecimalToHexadecimal.
// This class contains source code for converting 
// decimal number to hexadecimal.
public class DecimalToHexadecimal {

	// Create a main method with a signature such as 
	// public static void main(String[] args). This method
	// contains all the conversion logic. It is the starting
	// point of execution of any Java program.
	public static void main(String[] args) {

		// Create a Scanner object with the help of System.in instance.
		// System.in instance helps Scanner class in reading user inputs
		// from the console.
		Scanner scanner = new Scanner(System.in);

		// Prompt the user to enter a decimal number whose
		// conversion to hexadecimal number is to be done.
		System.out.print("Enter a decimal number - ");
		
		// Create a variable by name decimal. Using scanner class nextInt
		// method take integer value entered by user and assign it to 
		// decimal varuable.
		int decimal = scanner.nextInt();

		// Create a empty String variable which will hold our hexadecimal number.
		String hexadecimal = "";

		// In order to convert decimal number to hexadecimal number. We will
		// iterate using while loop till decimal is not equal to zero.
		while (decimal != 0) {

			// Create a int variable by name hexValue which will hold remainder
			// of decimal number with 16. In order to convert decimal to hexadecimal 
			// we have to divide decimal number by 16 and hold its remainder.
			int hexValue = decimal % 16; 
			
			// Create a char variable by name hexChar. This will help us in holding 
			// hexadecimal numbers which have characters from A to F.
			char hexChar;		

			// If the hexValue which is the remainder of decimal number with 16,
			// comes out to be less than 9. Than take hexValue appended with '0'
			// character and store it in hexChar variable.
			if (hexValue <= 9 && hexValue >= 0) {
				hexChar =  (char)(hexValue + '0'); 
			}
			else {  
				// Else if hexValue comes out to be greater than 9, than we have to append 
				// character A to it because after 9 instead of 10, 11, 12 it has to be output as
				// A, B and C so on .
				hexChar =  (char)(hexValue - 10 + 'A');
			}
			
			// Assign hexChar value appended with hexadecimal and assign it back to 
			// hexadecimal variable.	For each iteration of while loop we have to take 
			// previous hexadecimal value, append it to new hexChar and assign it back 
			// to hexadecimal.
			hexadecimal = hexChar + hexadecimal;
			
			// Follow the process  with new value of decimal, taking in division of decimal by 16.
			decimal = decimal / 16;
		} 

		// Finally printing the hexadecimal value on the Java console.
		System.out.println("The hexadecimal number is " + hexadecimal);
	}
}

Steps to implement -

Step 1 - Import necessary Java classes from Java API used in the tutorial. Scanner class is in java.util package. It is been used here to take user inputs from console.

Step 2 - Create a Java class such as "DecimalToHexadecimal". This class contains source code for converting decimal number to hexadecimal.

Step 3 - Create a main method with a signature such as public static void main(String[] args). This method contains all the conversion logic. It is the starting point of execution of any Java program.

Step 4 - Create a Scanner object with the help of System.in instance. System.in instance helps Scanner class in reading user inputs from the console.

Step 5 - Prompt the user to enter a decimal number whose conversion to hexadecimal number is to be done.

Step 6 - Create a variable by name decimal. Using scanner class nextInt method take integer value entered by user and assign it to decimal variable.

Step 7 - Create a empty String variable which will hold our hexadecimal number.

Step 8 - In order to convert decimal number to hexadecimal number. We will iterate using while loop till decimal is not equal to zero.

Step 9 - Create a int variable by name hexValue which will hold remainder of decimal number with 16. In order to convert decimal to hexadecimal we have to divide decimal number by 16 and hold its remainder.

Step 10 - Create a char variable by name hexChar. This will help us in holding hexadecimal numbers which have characters from A to F.

Step 11 - If the hexValue which is the remainder of decimal number with 16, comes out to be less than 9. Than take hexValue appended with '0' character and store it in hexChar variable.

Step 12 - Else if hexValue comes out to be greater than 9, than we have to append character A to it because after 9 instead of 10, 11, 12 it has to be output as A, B and C so on .

Step 13 - Assign hexChar value appended with hexadecimal and assign it back to hexadecimal variable. For each iteration of while loop we have to take previous hexadecimal value, append it to new hexChar and assign it back to hexadecimal.

Step 14 - Follow the process with new value of decimal, taking in division of decimal by 16.

Step 15 - Finally printing the hexadecimal value on the Java console.

Java program to convert decimal number to hexadecimal number.
Java program to convert decimal number to hexadecimal number.

Output of the program -

Output of the Java program to convert decimal number to hexadecimal number.
Output of the Java program to convert decimal number to hexadecimal number.
Output of the Java program to convert decimal number to hexadecimal number.
Output of the Java program to convert decimal number to hexadecimal number.
Output of the Java program to convert decimal number to hexadecimal number.
Output of the Java program to convert decimal number to hexadecimal number.

Output of the program - Explanation

On running above Java program, it prompts user to enter value of decimal number whose hexadecimal number is to be calculated. User enters a decimal number and hit enter key. The Java code converts decimal number to hexadecimal number and prints hexadecimal number on the console.

For example -

  1. User enters decimal number as 125. It prints hexadecimal number as 7D.
  2. User enters decimal number as 127. It prints hexadecimal number as 7F.
  3. User enters decimal number as 453. It prints hexadecimal number as 1C5.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)