-
Notifications
You must be signed in to change notification settings - Fork 0
/
hexaToOcta.java
42 lines (34 loc) · 1.08 KB
/
hexaToOcta.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.Scanner;
public class Exercise30 {
public static int hex_to_decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16 * val + d;
}
return val;
}
public static void main(String args[]) {
String hexdec_num;
int dec_num, i = 1, j;
int octal_num[] = new int[100];
Scanner in = new Scanner(System.in);
System.out.print("Input a hexadecimal number: ");
hexdec_num = in.nextLine();
// Convert hexadecimal to decimal
dec_num = hex_to_decimal(hexdec_num);
// Convert decimal to octal
while (dec_num != 0) {
octal_num[i++] = dec_num % 8;
dec_num = dec_num / 8;
}
System.out.print("Equivalent of octal number is: ");
for (j = i - 1; j > 0; j--) {
System.out.print(octal_num[j]);
}
System.out.print("\n");
}
}