Decimal to Hexadecimal Conversion in Java
Decimal to Hexadecimal Conversion
On this page we will learn to the logic to convert Decimal to Hexadecimal. And then learn to create Java program for Decimal to Hexadecimal Conversion.
Method 1
To know how to solve this you must first have knowledge of ASCII Table. The program works in two cases
- If the current remainder left >= 10
- Must be replaced by (A – F)
- Else if current remainder < 10
- Must be replaced by (0- 9)
Java Code
Run
public class Main { public static void main (String[]args) { int decimal = 1457; convert (decimal); } static void convert (int num) { // creating a char array to store hexadecimal equivalent char[] hexa = new char[100]; // using i to store hexadecimal bit at given array position int i = 0; while (num != 0) { int rem = 0; rem = num % 16; // check if rem < 10 : Digits : 0 - 9 // ascii 0 : 48 if (rem < 10) { hexa[i] = (char) (rem + 48); i++; } // else positional values : A - F // rem value will be > 10, adding 55 will result : A - F // ascii A : 65, B : 66 ..... F : 70 else { hexa[i] = (char) (rem + 55); i++; } num = num / 16; } // printing hexadecimal array in reverse order System.out.println ("Hexadecimal:"); for (int j = i - 1; j >= 0; j--) System.out.print (hexa[j]); } }
Output
Hexadecimal : 5B1
For similar Questions click on given button.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
public static StringBuilder decimalToHexaDecimalApproach2(int number) {
// Approach 1
StringBuilder binary = new StringBuilder();
String allHex = “0123456789ABCDEF”;
int remainderNumber;
while (number > 0) {
remainderNumber = number % 16;
if (remainderNumber <= 9) {
binary.insert(0, remainderNumber);
} else {
binary.insert(0,allHex.charAt(remainderNumber));
}
number /= 16;
}
return binary;
}
import java.util.*;
class main{
static String hexa(int n){
int decimal = n;
String req = “123456789ABCDEF”;
StringBuilder hexa = new StringBuilder();
while(n>16){
hexa.append(req.charAt((n%16)-1));
n/=16;
}
hexa.append(n);
return “Decimal : “+decimal+” == HexaDecimal : “+hexa.reverse().toString();
}
public static void main(String[] args) {
int n = 1457;
System.out.println(hexa(n));
}
}
package com.company;
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(“enter the decimal number”);
int n=input.nextInt();
int l=0,b=0;
char a;String st=””;
String s=”0123456789ABCDEF”;
while(n!=0)
{
b=n%16;
a=s.charAt(b);
st=a+st;
n=n/16;
}
System.out.print(st);
}