Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions bit_manipulation/single_bit_manipulation_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down