Skip to content

Instantly share code, notes, and snippets.

@ellenia
Created October 2, 2017 03:07
Show Gist options
  • Save ellenia/8e9a15adf505d55d6951c6835b96faff to your computer and use it in GitHub Desktop.
Save ellenia/8e9a15adf505d55d6951c6835b96faff to your computer and use it in GitHub Desktop.
Convert Hexadecimal number to Binary, Decimal and Octal in Java
/**
*
* Java program to convert Hexadecimal to binary, decimal and Octal in Java.
* Hexadecimal is base 16, Decimal number is base 10, Octal is base 8
* and Binary is base 2 number which has just two numbers 0 and 1.
* @author
*/
public class ConvertHexaToDecimal {
public static void main(String args[]) {
// Ask user to enter an Hexadecimal number in Console
System.out.println("Please enter Hexadecimal number : ");
Scanner scanner = new Scanner(System.in);
String hexadecimal = scanner.next();
//Converting Hexa decimal number to Decimal in Java
int decimal = Integer.parseInt(hexadecimal, 16);
System.out.println("Converted Decimal number is : " + decimal);
//Converting hexa decimal number to binary in Java
String binary = Integer.toBinaryString(decimal);
System.out.printf("Hexadecimal to Binary conversion of %s is %s %n", hexadecimal, binary );
// Converting Hex String to Octal in Java
String octal = Integer.toOctalString(decimal);
System.out.printf("Hexadecimal to Octal conversion of %s is %s %n", hexadecimal, octal );
}
}
Output:
Please enter Hexadecimal number :
A
Converted Decimal number is : 10
Hexadecimal to Binary conversion of A is 1010
Hexadecimal to Octal conversion of A is 12
Please enter Hexadecimal number :
-B
Converted Decimal number is : -11
Hexadecimal to Binary conversion of -B is 11111111111111111111111111110101
Hexadecimal to Octal conversion of -B is 37777777765
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment