Java Program to Convert Binary to Hexadecimal
Last Updated :
02 Aug, 2024
The Hexadecimal number system as the name suggests comprises 16 entities. These 16 entities consist of 10 digits, 0-9 representing the first 10 numbers of the hexadecimal system as well. For the remaining 6 numbers, we use English alphabets ranging from A through F to represent the numbers 10 to 15. It should be noted that the lowest number in the hexadecimal system is 0 with the highest being 15 represented by F. A hexadecimal number can be derived from a binary number by clubbing 4 digits to constitute a single character of the hexadecimal number.
Example:
Input: 11011111
Output: DF
Input: 10001101
Output: 8D
- In the above example, the binary number 10001101 can be broken down into chunks of 4 bits such as 1000 and 1101 which act as 2 characters for the corresponding hexadecimal number.
- The resultant hexadecimal number would be 8D where every character is determined by calculating its corresponding value in the decimal system and replacing it with an alphabet if it is a two-digit number in this case D which represents 13. The hexadecimal system is also referred to as base-16.
For the conversion of binary to hexadecimal, we are going to use the following two approaches :
- Using the toHexString() builtin java method
- Repeatedly getting the remainder and dividing the converted decimal number by 16
Approach 1:
Using this approach, we first convert the binary number to a decimal number which is stored as an Integer. Then, we simply use the toHexString() method of java to generate the desired output string.
Syntax :
public static String toHexString(int num)
Parameter:
- num - This parameter specifies the number which is to be converted
to a Hexadecimal string. The data-type is int.
Return Value: The function returns a string representation of the int argument as an unsigned integer in base 16.
Algorithm :
- Convert the binary number to a decimal number.
- To convert the binary number to a decimal number, first, extract each digit using by getting the remainder by dividing by 10.
- Next, multiply this digit with increasing powers of 2.
- Keep on dividing the original binary number by 10 to eliminate the last digit in each iteration.
- After having gotten the decimal number, just use the toHexString() method to get the desired output.
Example:
Java
// Java program to convert binary to hexadecimal
class GFG {
// method to convert binary to decimal
int binaryToDecimal(long binary)
{
// variable to store the converted
// binary number
int decimalNumber = 0, i = 0;
// loop to extract the digits of the binary
while (binary > 0) {
// extracting the digits by getting
// remainder on dividing by 10 and
// multiplying by increasing integral
// powers of 2
decimalNumber
+= Math.pow(2, i++) * (binary % 10);
// updating the binary by eliminating
// the last digit on division by 10
binary /= 10;
}
// returning the decimal number
return decimalNumber;
}
// method to convert decimal to hexadecimal
String decimalToHex(long binary)
{
// variable to store the output of the
// binaryToDecimal() method
int decimalNumber = binaryToDecimal(binary);
// converting the integer to the desired
// hex string using toHexString() method
String hexNumber
= Integer.toHexString(decimalNumber);
// converting the string to uppercase
// for uniformity
hexNumber = hexNumber.toUpperCase();
// returning the final hex string
return hexNumber;
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
long num = 10011110;
// calling and printing the output
// of decimalToHex() method
System.out.println("Inputted number : " +num);
System.out.println(ob.decimalToHex(10011110));
}
}
OutputInputted number : 10011110
9E
Time complexity: O(log N) where N is the input binary number, since the number of iterations in the while loop is proportional to the number of digits in the binary number.
Auxiliary space: O(1)
Approach 2:
- Under the second approach, we again first convert the binary number to a decimal number.
- Then we continuously divide and get the remainder of this decimal number to get the single character for each set of 4 bits we can find in the original binary number.
Algorithm:
- Convert the binary to a decimal using steps 2-4 in the above algorithm.
- Next, run a while loop with the terminating condition that the decimal number becomes 0 and the updating condition that the decimal number is divided by 16 in each iteration.
- In each iteration get the remainder by dividing the number by 16.
- Constitute a new String and keep on adding characters which are the remaining on dividing by 16.
- If the remainder is greater than or equal to 10 replace it with alphabets A-F depending on the remainder.
Example:
Java
// Java program to convert binary to hexadecimal
class GFG {
// method to convert binary to decimal
int binaryToDecimal(long binary)
{
// variable to store the converted binary
int decimalNumber = 0, i = 0;
// loop to extract digits of the binary
while (binary > 0) {
// extracting each digit of the binary
// by getting the remainder of division
// by 10 and multiplying it by
// increasing integral powers of 2
decimalNumber
+= Math.pow(2, i++) * (binary % 10);
// update condition of dividing the
// binary by 10
binary /= 10;
}
// returning the decimal
return decimalNumber;
}
// method to convert decimal to hex
String decimalToHex(long binary)
{
// variable to store the output of
// binaryToDecimal() method
int decimalNumber = binaryToDecimal(binary);
// character array to represent double
// digit remainders
char arr[] = { 'A', 'B', 'C', 'D', 'E', 'F' };
// variable to store the remainder on
// division by 16
int remainder, i = 0;
// declaring the string that stores the
// final hex string
String hexNumber = "";
// loop to convert decimal to hex
while (decimalNumber != 0) {
// calculating the remainder of decimal
// by dividing by 16
remainder = decimalNumber % 16;
// checking if the remainder is >= 10
if (remainder >= 10)
// replacing with the corresponding
// alphabet from the array
hexNumber = arr[remainder - 10] + hexNumber;
else
hexNumber = remainder + hexNumber;
// update condition of dividing the
// number by 16
decimalNumber /= 16;
}
// returning the hex string
return hexNumber;
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
long num =11000011;
// printing and calling the
// decimalToHex() method
System.out.println("Input : "+num);
System.out.println("Output : " +ob.decimalToHex(num));
}
}
OutputInput : 11000011
Output : C3
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read