-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
test_bitwise.py
57 lines (47 loc) · 1.19 KB
/
test_bitwise.py
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
"""Bitwise operators
@see: https://www.w3schools.com/python/python_operators.asp
Bitwise operators manipulate numbers on bit level.
"""
def test_bitwise_operators():
"""Bitwise operators"""
# AND
# Sets each bit to 1 if both bits are 1.
#
# Example:
# 5 = 0b0101
# 3 = 0b0011
assert 5 & 3 == 1 # 0b0001
# OR
# Sets each bit to 1 if one of two bits is 1.
#
# Example:
# 5 = 0b0101
# 3 = 0b0011
assert 5 | 3 == 7 # 0b0111
# NOT
# Inverts all the bits.
assert ~5 == -6
# XOR
# Sets each bit to 1 if only one of two bits is 1.
#
# Example:
# 5 = 0b0101
# 3 = 0b0011
number = 5 # 0b0101
number ^= 3 # 0b0011
assert 5 ^ 3 == 6 # 0b0110
# Signed right shift
# Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost
# bits fall off.
#
# Example:
# 5 = 0b0101
assert 5 >> 1 == 2 # 0b0010
assert 5 >> 2 == 1 # 0b0001
# Zero fill left shift
# Shift left by pushing zeros in from the right and let the leftmost bits fall off.
#
# Example:
# 5 = 0b0101
assert 5 << 1 == 10 # 0b1010
assert 5 << 2 == 20 # 0b10100