-
Notifications
You must be signed in to change notification settings - Fork 0
/
dec2oct.c
41 lines (35 loc) · 883 Bytes
/
dec2oct.c
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
/* converts decimal to octal */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int dtoo(const char *s);
int main(int argc, char **argv)
{
if(argc != 2) {
printf("Converts character string from decimal to octal notation\n"
"Usage: ./dec2oct STRING\n"
"Example ./dec2oct 100\n"
);
return -1;
}
printf("Decimal: %s\nOctal: %d\n", argv[1], dtoo(argv[1]));
return 0;
}
/* converts a string of decimal digits to octal*/
int dtoo(const char *s)
{
int decimal;
int result;
int power;
decimal = atoi(s);
/* convert decimal to octal by division */
power = result = 0;
while(decimal / 8 != 0) {
result += decimal % 8 * pow(10, power);
decimal /= 8;
++power;
}
result += decimal % 8 * pow(10,power);
return result;
}