-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprint_binary.h
79 lines (55 loc) · 1.58 KB
/
print_binary.h
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int get_bit(int number, int place){
int shifted_one = 1<<place;
int shifted_bit = shifted_one&number;
int bit = shifted_bit>>place;
return bit;
}
void print_binary(int number, int n_places){
// set n_places to 0 to print everything
// TODO need to figure out how null or nan or infinity work in c
int n_bytes = sizeof(number);
int n_bits = n_bytes*8;
int started = 0;
int has_defined_start = n_places!=0;// n_places!=NULL;
int print_bit;
for (int i=0;i<n_bits;i++){
int place = n_bits-i-1;
int bit = get_bit(number, place);
started = started|bit;
if (has_defined_start){
print_bit = place<n_places;
}else{
print_bit = started;
}
if (print_bit){
printf("%d",bit);
}
}
printf("\n");
}
int example(){
int a = pow(2,31)-2;
// char pointers are 1 byte so i can look at 1 byte at a time of a 4 byte integer :D
unsigned char* ptr = (unsigned char*)&a;
for (int i=3;i>=0;i--){
unsigned char* shifted_ptr = ptr+i;
printf("%p: ", shifted_ptr);
print_binary(*shifted_ptr,8);
}
return 0;
}
void get_binary_of_floating_point(float a_float){
float* pnt_to_float = &a_float;
int* pnt_to_int = (int*) pnt_to_float;
int a_int = *pnt_to_int;
// absolute beautiful code :)
if (a_float<10){
printf("%d: ",(int) a_float);
}else{
printf("%d: ",(int) a_float);
}
print_binary(a_int,0);
}