mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Bit manipulation: get the bit at a given position (#4438)
This commit is contained in:
parent
7d7c7972ae
commit
8d173438c3
|
@ -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
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user