Skip to content

Commit 6efaddb

Browse files
authored
Merge pull request TheAlgorithms#316 from The-TJ/patch-1
Add Hexadecimal to Octal
2 parents 3bfca30 + 27839d2 commit 6efaddb

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Conversions/HexToOct.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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+
}

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