-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary.c
51 lines (44 loc) · 806 Bytes
/
binary.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
46
47
48
49
50
51
# include <stdio.h>
# define BITS_IN_INT 32
// compute the sum of the digits of a decimal number
// 1234 = 10
int sum_of_decimal_digits(int n) {
int sum = 0;
while (n > 0) {
sum = sum + n % 10;
n = n / 10
}
return sum;
}
int sum_of_bits (int n) {
int sum = 0;
while (n > 0) {
sum = sum + (n & 0b1);
n = n >> 1;
}
return sum;
}
void print_bin(int n) {
if (n == 0) {} else {
print_bin(n >> 1);
printf("%d", n & 0b1); // is a recursive boi
}
}
void print_binary(int n) {
const int bits_in_int = 32;
char bits[bits_in_int];
int i = 0;
while (n > 0) {
bits[i++] = n & 0b1;
n = n >> 1; // >> is shift right (divide by 2)
}
for (int j = i - 1; j >= 0; j--) {
printf("%d", bits[j]);
}
printf("\n");
}
int main() {
print_bin(0b110111101);
printf("\n");
return 0;
}