-
Notifications
You must be signed in to change notification settings - Fork 0
/
truncate.c
45 lines (40 loc) · 1.06 KB
/
truncate.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
#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() {
long d;
printf("Enter a number: ");
scanf("%ld", &d);
printf("You said %ld!\n", d);
char binary[32];
get_binary(d, binary);
printf("That means %32s in binary!\n", binary);
short s = (short) d;
printf("If you turn it into a short, it becomes %d\n", s);
get_binary(s, binary);
printf("That means %32s in binary!\n", binary);
return 0;
}