Skip to content

Commit 8d17343

Browse files
authored
Bit manipulation: get the bit at a given position (TheAlgorithms#4438)
1 parent 7d7c797 commit 8d17343

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

bit_manipulation/single_bit_manipulation_operations.py

+20
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,26 @@ def is_bit_set(number: int, position: int) -> bool:
7474
return ((number >> position) & 1) == 1
7575

7676

77+
def get_bit(number: int, position: int) -> int:
78+
"""
79+
Get the bit at the given position
80+
81+
Details: perform bitwise and for the given number and X,
82+
Where X is a number with all the bits – zeroes and bit on given position – one.
83+
If the result is not equal to 0, then the bit on the given position is 1, else 0.
84+
85+
>>> get_bit(0b1010, 0)
86+
0
87+
>>> get_bit(0b1010, 1)
88+
1
89+
>>> get_bit(0b1010, 2)
90+
0
91+
>>> get_bit(0b1010, 3)
92+
1
93+
"""
94+
return int((number & (1 << position)) != 0)
95+
96+
7797
if __name__ == "__main__":
7898
import doctest
7999

0 commit comments

Comments
 (0)