Given a decimal number N, convert N into an equivalent hexadecimal number i.e. convert the number with base value 10 to base value 16. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value.
Examples of Decimal to Hexadecimal Conversion
Input : 10
Output: A
Input : 2545
Output: 9F1
Algorithm
- Store the remainder when the number is divided by 16 in an array.
- Divide the number by 16 now
- Repeat the above two steps until the number is not equal to 0.
- Print the array in reverse order now.
Program for Decimal to Hexadecimal Conversion in Java
Java
import java.io.*;
public class GFG {
static void decTohex(int n)
{
int[] hexNum = new int[100];
int i = 0;
while (n != 0) {
hexNum[i] = n % 16;
n = n / 16;
i++;
}
for (int j = i - 1; j >= 0; j--) {
if (hexNum[j] > 9)
System.out.print((char)(55 + hexNum[j]));
else
System.out.print(hexNum[j]);
}
}
public static void main(String[] args)
{
int n = 2545;
decTohex(n);
}
}
|
The complexity of the above method:
Time Complexity: O(log N)
Auxiliary Space: O(1)
Another Method Using Integer.toString()
The java.lang.Integer.toString(int a, int base) is an inbuilt method in Java that is used to return a string representation of the argument in the base, specified by the second argument base. If the radix/base is smaller than the Character.MIN_RADIX or larger than Character.MAX_RADIX, then the base 10 is used. The ASCII characters are used as digits: 0 to 9 and a to z.
Syntax
public static String toString(int a, int base)
Parameter: The method accepts two parameters:
- a: This is of integer type and refers to the integer value that is to be converted.
- base: This is also of integer type and refers to the base that is to be used while representing the strings.
Return Value: The method returns a string representation of the specified argument in the specified base.
Examples:
Input: a = 71, base = 2
Output: 1000111
Input: a = 314, base = 16
Output: 13a
Java Program to Convert Decimal to Hexadecimal using Integer.toString() Method
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
int number = 2545;
System.out.println(Integer.toString(number, 16));
}
}
|
Complexity of the above method
Time complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
04 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...