×

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10 to 15 are represented by alphabets from A to F. There are two methods to convert Hexadecimal to decimal are as follows:
  • Using toHexString() method
  • Using user-defined logic
Using Integer.toHexString() method The toHexString() is a static method of Integer wrapper class.It accepts a single parameter of integer type and returns a string representation of int argument in radix16.  The signature of the method is given below: public static String toHexString(int decimal_number) Where decimal_number is the number which you want to convert. Example In the following example, we have taken two variables str1 and str2 of type String which stores the converted Hexadecimal value. The toHexString() is the method of Integer wrapper class which parses the integer arguments 34 and 75 respectively. The first println statement prints the hexadecimal representation of 34 and the second println statement prints the hexadecimal representation of 75.
public class DecimalToHexaExample
{  
public static void main(String args[])
{  
String str1=Integer.toHexString(34);
String str2=Integer.toHexString(75);
System.out.println(str1);  
System.out.println(str2);  
}
}
Output
22
4b
Using user-defined logic You can convert decimal to hexadecimal in using user-defined logic. Example In the following example, we have taken two variablesdecnum (represent decimal number) and rem (represent remainder). We have initialized 45 todecnum. A String type variable hexdecnum initialized to null and it stores the convertedhexadecimal value.We have defined an array hex[]of type charand initialized hexadecimal valuesfrom 0 to F to it. The while loop has the condition decnnum>0 which will repeatedly perform the operations in the while block until decnumis greater than 0 otherwise terminate the execution.The body of the while loop contains three statements. The first statement finds the remainder on dividing decnum by 16, which is obtained by using a modulo operator. In the second statement, the hex[rem] converts the remainder (rem) into character equivalent and concatenates theremainder(rem) into hexdecnum,and stores the results into the variable hexdecnum. The third statement updates the value ofdecnum, i.e., it divides the value by 16 and takes the quotient. These steps perform the operation in the while block until the conditiondecnum>0 becomes false. When the execution of the while loop is completed the println statement prints the hexadecimalrepresentation of the variable decnum which is stores in hexdecnum. It prints the array in reverse order. Remember:If you write the second statement of while loop like this: hexdecnum=hex[rem]+hexdecnum then the output will be 2D.When you change the sequence of the seconds tatement i.e. hexdecnum=hexdecnum+hex[rem]then the hexadecimal representation of 45 will be D2 which is the wrong output.So remember the sequence while you write this statement. This statement performs concatenation instead of addition. One more thing to remember, if you assign any digitamong0 to 9it gives the same digit as output but in string form.
public class DecimalToHexaExample1
{
public static void main(String args[])
{
intdecnum=45, rem;
String hexdecnum="";
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(decnum>0)
{
rem = decnum%16;        
hexdecnum = hex[rem] + hexdecnum;
decnum = decnum/16;
}
System.out.println("Hexadecimal Value of 45 is:"+hexdecnum);
}
}
Output
Equivalent Hexadecimal Value of 0 is: 2D

Related Topics

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.