Skip to content

Commit 1b5c1b8

Browse files
authored
Add single bit manipulation operations. (TheAlgorithms#3284)
* Add single bit manipuation operations. * fixup! Add single bit manipuation operations. * Change wording.
1 parent 3a191d9 commit 1b5c1b8

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#!/usr/bin/env python3
2+
3+
"""Provide the functionality to manipulate a single bit."""
4+
5+
6+
def set_bit(number: int, position: int):
7+
"""
8+
Set the bit at position to 1.
9+
10+
Details: perform bitwise or for given number and X.
11+
Where X is a number with all the bits – zeroes and bit on given
12+
position – one.
13+
14+
>>> set_bit(0b1101, 1) # 0b1111
15+
15
16+
>>> set_bit(0b0, 5) # 0b100000
17+
32
18+
>>> set_bit(0b1111, 1) # 0b1111
19+
15
20+
"""
21+
return number | (1 << position)
22+
23+
24+
def clear_bit(number: int, position: int):
25+
"""
26+
Set the bit at position to 0.
27+
28+
Details: perform bitwise and for given number and X.
29+
Where X is a number with all the bits – ones and bit on given
30+
position – zero.
31+
32+
>>> clear_bit(0b10010, 1) # 0b10000
33+
16
34+
>>> clear_bit(0b0, 5) # 0b0
35+
0
36+
"""
37+
return number & ~(1 << position)
38+
39+
40+
def flip_bit(number: int, position: int):
41+
"""
42+
Flip the bit at position.
43+
44+
Details: perform bitwise xor for given number and X.
45+
Where X is a number with all the bits – zeroes and bit on given
46+
position – one.
47+
48+
>>> flip_bit(0b101, 1) # 0b111
49+
7
50+
>>> flip_bit(0b101, 0) # 0b100
51+
4
52+
"""
53+
return number ^ (1 << position)
54+
55+
56+
def is_bit_set(number: int, position: int) -> bool:
57+
"""
58+
Is the bit at position set?
59+
60+
Details: Shift the bit at position to be the first (smallest) bit.
61+
Then check if the first bit is set by anding the shifted number with 1.
62+
63+
>>> is_bit_set(0b1010, 0)
64+
False
65+
>>> is_bit_set(0b1010, 1)
66+
True
67+
>>> is_bit_set(0b1010, 2)
68+
False
69+
>>> is_bit_set(0b1010, 3)
70+
True
71+
>>> is_bit_set(0b0, 17)
72+
False
73+
"""
74+
return ((number >> position) & 1) == 1
75+
76+
77+
if __name__ == "__main__":
78+
import doctest
79+
80+
doctest.testmod()

0 commit comments

Comments
 (0)