forked from huangsam/ultimate-python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitwise.py
More file actions
Latest commit
50 lines (39 loc) · 1.98 KB
/
Copy pathbitwise.py
File metadata and controls
50 lines (39 loc) · 1.98 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
42
43
44
45
46
47
48
49
50
"""
Bitwise operators in Python allow you to manipulate individual bits of integers.
This module demonstrates the use of bitwise operators and their behavior.
"""
defmain() ->None:
# Define some integer values for demonstration
a=5# Binary: 0101
b=3# Binary: 0011
# Bitwise AND (&) operator compares each bit of two integers and returns 1
# if both bits are 1, otherwise returns 0
result_and=a&b# Binary: 0001 (Decimal: 1)
assertresult_and==1
# Bitwise OR (|) operator compares each bit of two integers and returns 1
# if at least one bit is 1, otherwise returns 0
result_or=a|b# Binary: 0111 (Decimal: 7)
assertresult_or==7
# Bitwise XOR (^) operator compares each bit of two integers and returns 1
# if the bits are different (one is 1 and the other is 0), otherwise returns 0
result_xor=a^b# Binary: 0110 (Decimal: 6)
assertresult_xor==6
# Bitwise NOT (~) operator inverts all bits of an integer
# It returns the one's complement of the integer
result_not_a=~a# Binary: 11111010 (Decimal: -6)
assertresult_not_a==-6
# Bitwise left shift (<<) operator shifts the bits of an integer to the left by
# a specified number of positions, filling with zeros
result_left_shift=a<<2# Binary: 010100 (Decimal: 20)
assertresult_left_shift==20
# Bitwise right shift (>>) operator shifts the bits of an integer to the right
# by a specified number of positions, filling with zeros for positive numbers
# and with ones for negative numbers
result_right_shift=a>>1# Binary: 0010 (Decimal: 2)
assertresult_right_shift==2
# Note that bitwise shifts have lower precedence than arithmetic operations
# https://docs.python.org/3/reference/expressions.html
result_right_shift_with_addition=a>>1+1# Equivalent to a >> (1 + 1)
assertresult_right_shift_with_addition==1# Binary: 0001 (Decimal: 1)
if__name__=="__main__":
main()