-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2_print_bits.c
More file actions
41 lines (34 loc) · 1.37 KB
/
Copy path2_print_bits.c
File metadata and controls
41 lines (34 loc) · 1.37 KB
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
/* ***************************************************************************
* Author : Kura Peng (kpeng) <https://github.com/sayakura>
* Created : 2018/10/05
* Updated : 2018/10/05
* ***************************************************************************/
#include <unistd.h>
void print_bits(unsigned char octet)
{
int i = 1;
i <<= 8;
while (i >>= 1)
(octet & i) ? write(1, "1", 1) : write(1, "0", 1);
}
// i = 256(1 0000 0000) at line 18 and i = 1000 0000 at the first while loop
// by using & operator, we can compare every bit of octect starting from the
// left to the right, and print 1 if there's 1.
/*------------------------------------------------------------------------------
int main(void)
{
print_bits(255);
return (0);
}
------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------
Assignment name : print_bits
Expected files : print_bits.c
Allowed functions: write
--------------------------------------------------------------------------------
Write a function that takes a byte, and prints it in binary WITHOUT A NEWLINE
AT THE END.
Your function must be declared as follows:
void print_bits(unsigned char octet);
Example, if you pass 2 to print_bits, it will print "00000010"
------------------------------------------------------------------------------*/