java convert decimal to hex code example
Example 1: Java convert hex to decimal
public class ConvertHexToDecimal
{
public static void main(String[] args)
{
String strHex = "b";
int decimal = Integer.parseInt(strHex, 16);
System.out.println("Decimal number : " + decimal);
}
}
Example 2: convert decimal to hexadecimal in java
public class DecimalToHexExample2{
public static String toHex(int decimal){
int rem;
String hex="";
char hexchars[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(decimal>0)
{
rem=decimal%16;
hex=hexchars[rem]+hex;
decimal=decimal/16;
}
return hex;
}
public static void main(String args[]){
System.out.println("Hexadecimal of 10 is: "+toHex(10));
System.out.println("Hexadecimal of 15 is: "+toHex(15));
System.out.println("Hexadecimal of 289 is: "+toHex(289));
}}
Example 3: convert decimal to binary in java
public class DecimalToBinaryExample2{
public static void toBinary(int decimal){
int binary[] = new int[40];
int index = 0;
while(decimal > 0){
binary[index++] = decimal%2;
decimal = decimal/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
System.out.println();//new line
}
public static void main(String args[]){
System.out.println("Decimal of 10 is: ");
toBinary(10);
System.out.println("Decimal of 21 is: ");
toBinary(21);
System.out.println("Decimal of 31 is: ");
toBinary(31);
}}
Example 4: convert int to hex java
int integer = 18;
String hexString = Integer.toHexString(integer);
Example 5: Java convert decimal to hex
import java.util.Scanner;
public class DecimalToHexaExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter decimal number: ");
int decimal = sc.nextInt();
String strHexadecimal = "";
while(decimal != 0)
{
int hexNumber = decimal % 16;
char charHex;
if(hexNumber <= 9 && hexNumber >= 0)
{
charHex = (char)(hexNumber + '0');
}
else
{
charHex = (char)(hexNumber - 10 + 'A');
}
strHexadecimal = charHex + strHexadecimal;
decimal = decimal / 16;
}
System.out.println("Hexadecimal number: " + strHexadecimal);
sc.close();
}
}