File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed
Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ + * Converts any Hexadecimal Number to Octal
3+ + *
4+ + * @author Tanmay Joshi
5+ + *
6+ + */
7+ import java .util .Scanner ;
8+
9+ public class HexToOct
10+ {
11+ /**
12+ + * This method converts a Hexadecimal number to
13+ + * a decimal number
14+ + *
15+ + * @param The Hexadecimal Number
16+ + * @return The Decimal number
17+ + */
18+ public static int hex2decimal (String s )
19+ {
20+ String str = "0123456789ABCDEF" ;
21+ s = s .toUpperCase ();
22+ int val = 0 ;
23+ for (int i = 0 ; i < s .length (); i ++)
24+ {
25+ char a = s .charAt (i );
26+ int n = str .indexOf (a );
27+ val = 16 *val + n ;
28+ }
29+ return val ;
30+ }
31+
32+ /**
33+ + * This method converts a Decimal number to
34+ + * a octal number
35+ + *
36+ + * @param The Decimal Number
37+ + * @return The Octal number
38+ + */
39+ public static int decimal2octal (int q )
40+ {
41+ int now ;
42+ int i =1 ;
43+ int octnum =0 ;
44+ while (q >0 )
45+ {
46+ now =q %8 ;
47+ octnum =(now *(int )(Math .pow (10 ,i )))+octnum ;
48+ q /=8 ;
49+ i ++;
50+ }
51+ octnum /=10 ;
52+ return octnum ;
53+ }
54+ // Main method that gets the hex input from user and converts it into octal.
55+ public static void main (String args [])
56+ {
57+ String hexadecnum ;
58+ int decnum ,octalnum ;
59+ Scanner scan = new Scanner (System .in );
60+
61+ System .out .print ("Enter Hexadecimal Number : " );
62+ hexadecnum = scan .nextLine ();
63+
64+ // first convert hexadecimal to decimal
65+
66+ decnum = hex2decimal (hexadecnum ); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
67+
68+ // convert decimal to octal
69+ octalnum =decimal2octal (decnum );
70+ System .out .println ("Number in octal: " +octalnum );
71+
72+
73+ }
74+ }
You can’t perform that action at this time.
0 commit comments