Create HextoDec.java

Program that converts Hexadecimal numbers to decimal.
This commit is contained in:
The-TJ 2017-11-17 12:32:45 +00:00 committed by GitHub
parent df6838ede3
commit 37838f6237
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

49
Conversions/HexToOct.java Normal file
View File

@ -0,0 +1,49 @@
/* Java Program - Convert Hexadecimal to Octal
Author - Tanmay Joshi*/
import java.util.Scanner;
public class HexToOct
{
public static int hex2decimal(String s)
{
String str = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
{
char a = s.charAt(i);
int n = str.indexOf(a);
val = 16*val + n;
}
return val;
}
public static void main(String args[])
{
String hexadecnum;
int decnum, i=1, j;
int octnum[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal
decnum = hex2decimal(hexadecnum);
// convert decimal to octal
while(decnum != 0)
{
octnum[i++] = decnum%8;
decnum = decnum/8;
}
System.out.print("Equivalent Octal Number is :\n");
for(j=i-1; j>0; j--)
{
System.out.print(octnum[j]);
}
}
}