Java Program to illustrate the Usage of HexaDecimal
Last Updated :
16 Nov, 2022
A decimal number is the sum of digits multiplied with a power of 10. Decimal numbers are represented with base 10 whereas hexadecimal Number is the sum of digits multiplied with the power of 16, somehow there are similar traits in the internal working of them just they are two different ways to present a number. The hexadecimal system has 16 different digit symbols. Different numbers can be generated using the combination of digits from 0 to 15. The representation in the hexadecimal system is the same as the decimal number system from 0 to 9 but then onwards it changes.
Representation:
Decimal Number Hexadecimal Number Equivalent
0 —> 0
: :
9 —> 9
10 —> A
11 —> B
12 —> C
13 —> D
14 —> E
15 —> F
Illustration: Internal Working
A. Decimal to Hexadecimal Number System
(1) (13)10 --> (D)16
Directly can be written 13 as D in hexadecimal system
(2) (16)10 ---> (10)16
( 16 )16 = ( 1 x 161) + ( 0 * 160)
(3) (59)10 ---> (3B)16
( 59 )10 --> ( 3 * 161) + (11 * 160)
Conclusion:
For a Decimal Number system-> ( 421 )10 = (4 x 102) + (2 x 101) + (1 x 100)
B. Similarly ,Hexadecimal to Decimal Number System
(8A)16 ---> (138)10
(8A)16 --> (8 x 161) + (10 x 160)
Conclusion:
In Java programs, hexadecimal numbers are written by placing 0x before numbers.
Below are 4 examples been discusses to illustrate the usage of Hexadecimal Number
- Converting Hex number to Decimal number
- Converting Decimal number to Hex number
- Converting Hex number to Long number
- Converting Long number to Hex number
Example 1: Java program to convert Hex number to Decimal number
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String hexNum = "100" ;
int decimal = Integer.parseInt(hexNum, 16 );
System.out.println( "Decimal value is " + decimal);
}
}
|
Output
Decimal value is 256
Example 2: Java program to convert Decimal number to Hex number
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 257 ;
String hex = Integer.toHexString(i);
System.out.println( "Hex value is " + hex);
}
}
|
Example 3: Java program to convert Hex number to Long number
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String hexNum = "10000" ;
long num = Long.parseLong(hexNum, 16 );
System.out.println( "Long value is " + num);
}
}
|
Output
Long value is 65536
Example 4: Java program to convert Long number to Hex number
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
long i = 1024 ;
String hex = Long.toHexString(i);
System.out.println( "Hex value is " + hex);
}
}
|
Note: There are two more conventions for hexadecimal numbers, 400h or $400. They both are the same as 0x400.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...