Skip to content

Commit 27839d2

Browse files
authored
Update HexToOct.java
1 parent 402c4e8 commit 27839d2

File tree

1 file changed

+41
-19
lines changed

1 file changed

+41
-19
lines changed

Conversions/HexToOct.java

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
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+
+ */
47
import java.util.Scanner;
58

69
public class HexToOct
710
{
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+
+ */
1018
public static int hex2decimal(String s)
1119
{
1220
String str = "0123456789ABCDEF";
@@ -20,12 +28,34 @@ public static int hex2decimal(String s)
2028
}
2129
return val;
2230
}
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+
}
2354
// Main method that gets the hex input from user and converts it into octal.
2455
public static void main(String args[])
2556
{
2657
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;
2959
Scanner scan = new Scanner(System.in);
3060

3161
System.out.print("Enter Hexadecimal Number : ");
@@ -34,19 +64,11 @@ public static void main(String args[])
3464
// first convert hexadecimal to decimal
3565

3666
decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
37-
67+
3868
// convert decimal to octal
69+
octalnum=decimal2octal(decnum);
70+
System.out.println("Number in octal: "+octalnum);
71+
3972

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-
}
5173
}
5274
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy