1
- /* Java Program - Convert Hexadecimal to Octal
2
- Author - Tanmay Joshi*/
3
-
1
+ /**
2
+ + * Converts any Hexadecimal Number to Octal
3
+ + *
4
+ + * @author Tanmay Joshi
5
+ + *
6
+ + */
4
7
import java .util .Scanner ;
5
8
6
9
public class HexToOct
7
10
{
8
- /*Function that takes the Hexadecimal number as input and returns the decimal form.
9
- The input is recieved as a string and the return type is int*/
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
+ + */
10
18
public static int hex2decimal (String s )
11
19
{
12
20
String str = "0123456789ABCDEF" ;
@@ -20,12 +28,34 @@ public static int hex2decimal(String s)
20
28
}
21
29
return val ;
22
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
+ }
23
54
// Main method that gets the hex input from user and converts it into octal.
24
55
public static void main (String args [])
25
56
{
26
57
String hexadecnum ;
27
- int decnum , i =1 , j ;
28
- int octnum [] = new int [100 ]; //Array to store the octal from of the hex number.
58
+ int decnum ,octalnum ;
29
59
Scanner scan = new Scanner (System .in );
30
60
31
61
System .out .print ("Enter Hexadecimal Number : " );
@@ -34,19 +64,11 @@ public static void main(String args[])
34
64
// first convert hexadecimal to decimal
35
65
36
66
decnum = hex2decimal (hexadecnum ); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
37
-
67
+
38
68
// convert decimal to octal
69
+ octalnum =decimal2octal (decnum );
70
+ System .out .println ("Number in octal: " +octalnum );
71
+
39
72
40
- while (decnum != 0 )
41
- {
42
- octnum [i ++] = decnum %8 ;
43
- decnum = decnum /8 ;
44
- }
45
- //Print the octal form of the number.
46
- System .out .print ("Equivalent Octal Number is :\n " );
47
- for (j =i -1 ; j >0 ; j --)
48
- {
49
- System .out .print (octnum [j ]);
50
- }
51
73
}
52
74
}
0 commit comments