2017-11-17 20:32:45 +08:00
|
|
|
/* Java Program - Convert Hexadecimal to Octal
|
|
|
|
Author - Tanmay Joshi*/
|
|
|
|
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
public class HexToOct
|
2017-11-23 01:38:51 +08:00
|
|
|
{
|
|
|
|
//Function that takes the Hexadecimal number as input and returns the decimal form.
|
2017-11-17 20:32:45 +08:00
|
|
|
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;
|
2017-11-23 01:38:51 +08:00
|
|
|
}
|
|
|
|
// Main function that gets the hex input from user and converts it into octal.
|
2017-11-17 20:32:45 +08:00
|
|
|
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;
|
|
|
|
}
|
2017-11-23 01:38:51 +08:00
|
|
|
//Print the octal form of the number.
|
2017-11-17 20:32:45 +08:00
|
|
|
System.out.print("Equivalent Octal Number is :\n");
|
|
|
|
for(j=i-1; j>0; j--)
|
|
|
|
{
|
|
|
|
System.out.print(octnum[j]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|