-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbin2.c
More file actions
49 lines (40 loc) · 897 Bytes
/
Copy pathbin2.c
File metadata and controls
49 lines (40 loc) · 897 Bytes
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
#include <stdio.h>
#include <stdint.h>
typedef uint8_t u8;
int getBinary(u8 n, int bits, char *output) {
for(int i = 0; i < bits; i++) {
int bit = (n >> (bits - 1 - i)) & 0x01;
output[i] = bit ? '1' : '0';
}
output[bits] = '\0';
return 0;
}
int setBinary(u8 n, int length, char * cReturn)
{
int i = 0;
u8 val = n;
if (cReturn == NULL)
return -1;
for (i = 0; i < length; i++)
{
if ((val & 0x1) == 1)
{
cReturn[length - i - 1] = '1';
}
else
{
cReturn[length - i - 1] = '0';
}
val >>= 1;
}
cReturn[length] = '\0';
return 0;
}
int main() {
char bin[9];
//getBinary(5, 8, bin);
//printf("Binary = %s\n", bin); // Output: 00000101
setBinary(13, 8, bin);
printf("Binary = %s\n", bin); // Output: 00000101
return 0;
}