Skip to content

Add single bit manipulation operations. #3284

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 3 commits into from
Oct 25, 2020
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
80 changes: 80 additions & 0 deletions bit_manipulation/single_bit_manipulation_operations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env python3

"""Provide the functionality to manipulate a single bit."""


def set_bit(number: int, position: int):
"""
Set the bit at position to 1.

Details: perform bitwise or for given number and X.
Where X is a number with all the bits – zeroes and bit on given
position – one.

>>> set_bit(0b1101, 1) # 0b1111
15
>>> set_bit(0b0, 5) # 0b100000
32
>>> set_bit(0b1111, 1) # 0b1111
15
"""
return number | (1 << position)


def clear_bit(number: int, position: int):
"""
Set the bit at position to 0.

Details: perform bitwise and for given number and X.
Where X is a number with all the bits – ones and bit on given
position – zero.

>>> clear_bit(0b10010, 1) # 0b10000
16
>>> clear_bit(0b0, 5) # 0b0
0
"""
return number & ~(1 << position)


def flip_bit(number: int, position: int):
"""
Flip the bit at position.

Details: perform bitwise xor for given number and X.
Where X is a number with all the bits – zeroes and bit on given
position – one.

>>> flip_bit(0b101, 1) # 0b111
7
>>> flip_bit(0b101, 0) # 0b100
4
"""
return number ^ (1 << position)


def is_bit_set(number: int, position: int) -> bool:
"""
Is the bit at position set?

Details: Shift the bit at position to be the first (smallest) bit.
Then check if the first bit is set by anding the shifted number with 1.

>>> is_bit_set(0b1010, 0)
False
>>> is_bit_set(0b1010, 1)
True
>>> is_bit_set(0b1010, 2)
False
>>> is_bit_set(0b1010, 3)
True
>>> is_bit_set(0b0, 17)
False
"""
return ((number >> position) & 1) == 1


if __name__ == "__main__":
import doctest

doctest.testmod()