Bit manipulation: get the bit at a given position (#4438)

This commit is contained in:
Cere Blanco
2021-05-18 22:54:34 +08:00
committed by GitHub
parent 7d7c7972ae
commit 8d173438c3

View File

@@ -74,6 +74,26 @@ def is_bit_set(number: int, position: int) -> bool:
return ((number >> position) & 1) == 1
def get_bit(number: int, position: int) -> int:
"""
Get the bit at the given position
Details: perform bitwise and for the given number and X,
Where X is a number with all the bits – zeroes and bit on given position – one.
If the result is not equal to 0, then the bit on the given position is 1, else 0.
>>> get_bit(0b1010, 0)
0
>>> get_bit(0b1010, 1)
1
>>> get_bit(0b1010, 2)
0
>>> get_bit(0b1010, 3)
1
"""
return int((number & (1 << position)) != 0)
if __name__ == "__main__":
import doctest