2017-11-27 04:36:39 +08:00
|
|
|
/**
|
|
|
|
+ * Converts any Hexadecimal Number to Octal
|
|
|
|
+ *
|
|
|
|
+ * @author Tanmay Joshi
|
|
|
|
+ *
|
|
|
|
+ */
|
2017-11-17 20:32:45 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
public class HexToOct
|
2017-11-23 01:38:51 +08:00
|
|
|
{
|
2017-11-27 04:36:39 +08:00
|
|
|
/**
|
|
|
|
+ * This method converts a Hexadecimal number to
|
|
|
|
+ * a decimal number
|
|
|
|
+ *
|
|
|
|
+ * @param The Hexadecimal Number
|
|
|
|
+ * @return The Decimal number
|
|
|
|
+ */
|
2017-11-17 20:32:45 +08:00
|
|
|
public static int hex2decimal(String s)
|
|
|
|
{
|
2017-11-23 01:43:48 +08:00
|
|
|
String str = "0123456789ABCDEF";
|
2017-11-17 20:32:45 +08:00
|
|
|
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
|
|
|
}
|
2017-11-27 04:36:39 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
+ * This method converts a Decimal number to
|
|
|
|
+ * a octal number
|
|
|
|
+ *
|
|
|
|
+ * @param The Decimal Number
|
|
|
|
+ * @return The Octal number
|
|
|
|
+ */
|
|
|
|
public static int decimal2octal(int q)
|
|
|
|
{
|
|
|
|
int now;
|
|
|
|
int i=1;
|
|
|
|
int octnum=0;
|
|
|
|
while(q>0)
|
|
|
|
{
|
|
|
|
now=q%8;
|
|
|
|
octnum=(now*(int)(Math.pow(10,i)))+octnum;
|
|
|
|
q/=8;
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
octnum/=10;
|
|
|
|
return octnum;
|
|
|
|
}
|
2017-11-23 01:43:48 +08:00
|
|
|
// Main method 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;
|
2017-11-27 04:36:39 +08:00
|
|
|
int decnum,octalnum;
|
2017-11-17 20:32:45 +08:00
|
|
|
Scanner scan = new Scanner(System.in);
|
|
|
|
|
|
|
|
System.out.print("Enter Hexadecimal Number : ");
|
2017-11-23 01:43:48 +08:00
|
|
|
hexadecnum = scan.nextLine();
|
2017-11-17 20:32:45 +08:00
|
|
|
|
|
|
|
// first convert hexadecimal to decimal
|
|
|
|
|
2017-11-23 01:43:48 +08:00
|
|
|
decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
|
2017-11-27 04:36:39 +08:00
|
|
|
|
2017-11-17 20:32:45 +08:00
|
|
|
// convert decimal to octal
|
2017-11-27 04:36:39 +08:00
|
|
|
octalnum=decimal2octal(decnum);
|
|
|
|
System.out.println("Number in octal: "+octalnum);
|
|
|
|
|
2017-11-17 20:32:45 +08:00
|
|
|
|
|
|
|
}
|
|
|
|
}
|