-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathbinary_to_octal.c
More file actions
54 lines (43 loc) · 1.06 KB
/
binary_to_octal.c
File metadata and controls
54 lines (43 loc) · 1.06 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
// Binary number to octal number conversion
#include <stdio.h>
// Function that returns the last three digits
int three_digits(int n)
{
int r, d = 0, p = 1;
for (int i = 0; i < 3; i++)
{
r = n % 10;
d += r * p;
p *= 10;
n /= 10;
}
return d;
}
int main(void)
{
int binary_num, d = 0, base = 1, remainder, td, res = 0, ord = 1;
printf("Enter the binary no: ");
scanf("%d", &binary_num);
while (binary_num > 0)
{
if (binary_num >
111) // Checking if binary number is greater than three digits
td = three_digits(binary_num);
else
td = binary_num;
binary_num /= 1000;
d = 0, base = 1;
// Converting the last three digits to decimal
while (td > 0)
{
remainder = td % 10;
td /= 10;
d += (base * remainder);
base *= 2;
}
res += d * ord; // Calculating the octal value
ord *= 10;
}
printf("\nOctal equivalent is: %d", res);
return 0;
}