From 8d173438c38cb7d92f6daf2c0e3405067bf4166f Mon Sep 17 00:00:00 2001 From: Cere Blanco <743526+cereblanco@users.noreply.github.com> Date: Tue, 18 May 2021 22:54:34 +0800 Subject: [PATCH] Bit manipulation: get the bit at a given position (#4438) --- .../single_bit_manipulation_operations.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/bit_manipulation/single_bit_manipulation_operations.py b/bit_manipulation/single_bit_manipulation_operations.py index e4a54028d..b43ff07b7 100644 --- a/bit_manipulation/single_bit_manipulation_operations.py +++ b/bit_manipulation/single_bit_manipulation_operations.py @@ -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