-
Notifications
You must be signed in to change notification settings - Fork 0
/
print_decimal.c
45 lines (40 loc) · 1.06 KB
/
print_decimal.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
42
43
44
45
// Ask for a decimal number and print it out as hex and binary.
// Also illustrates input from the command line.
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
// in real life we'd need to be careful about the size of the char array.
void get_binary(long decimal, char* binary) {
int index;
index = 0;
// a little sentinel to let us ignore leading zeroes.
bool leading = true;
int i;
for (i = 31; i >= 0; i--) {
long p = pow(2, i);
if (decimal >= p) {
binary[index] = '1';
decimal = decimal - p;
leading = false;
index++;
} else if (!leading) {
binary[index] = '0';
index++;
}
}
// terminate the array. When printf prints it, it'll stop here, rather than
// printing garbage for the unused parts of the array.
binary[index] = '\0';
}
int main() {
int d;
printf("Enter a decimal number: ");
scanf("%d", &d);
printf("You said %d!\n", d);
printf("That means %x in hex!\n", d);
int i;
char binary[32];
get_binary(d, binary);
printf("That means %s in binary!\n", binary);
return 0;
}