-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpart01.c
executable file
·79 lines (62 loc) · 1.96 KB
/
part01.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
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 <assert.h>
#include "util.h"
/*
The most basic bitwise operators are the left and right bitwise operators.
These operators work by shifting the bits over by a designated number
'b' of slots. Lets take a look at how these shifts work.
The block below shows how these operators work on the bit level.
Note that in the diagram the shifts or 'b', is and is usually written
as a decimal integer.
Left Bit Shift <<
00000001 << 2 = 00000100 (1 << 2 = 4)
00000101 << 3 = 00101000 (5 << 3 = 40)
Right Bit Shift >>
000010100 >> 3 = 00000010 (20 >> 3 = 2)
000000010 >> 2 = 00000000 (2 >> 2 = 0)
Note that shifting more than the size of the type is undefined behavior.
*/
char left_shift(char shift_me, int b)
{
/* TODO: implement me */
return (shift_me << b);
}
char right_shift(char shift_me, int b)
{
/* TODO: implement me */
return (shift_me >> b);
}
int main()
{
assert(left_shift(1, 2) == 4);
assert(left_shift(5, 3) == 40);
/* TODO: initialize x properly */
char x = 32;
assert(left_shift(4, 3) == x);
assert(right_shift(20, 3) == 2);
assert(right_shift(2, 2) == 0);
/* TODO: initialize y properly */
char y = 2;
assert(right_shift(16, 3) == y);
/* Note that you can use binary numbers
explicitly in your code with the following
notation. */
assert(left_shift(0b00000001, 2) == 4);
assert(right_shift(0b01000000, 3) == 8);
/* And I've provided you with a method to see
the binary representation of any char. */
print_in_binary(12);
/* But remember there are two types of shifts?
Logical, which is what we have above and
Arithmetic, which happens when we right shift
negative numbers.
*/
print_in_binary(0b10000000);
print_in_binary(right_shift(0b10000000, 1));
/* What happened at line 67? */
/* TODO: initialize z properly */
char z = -64;
assert(right_shift(0b10000000, 1) == z);
part_completed(1);
return 0;
}