Created
January 6, 2019 14:50
-
-
Save sergeyprokudin/4be24ca57a39e93b9da930604909d70c to your computer and use it in GitHub Desktop.
Bitwise operations: set clear bits, check set bits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def set_bit(x, i): | |
bi = 0b1 << i | |
return x | bi | |
def xor_bit(x, i): | |
bi = 0b1 << i | |
return x ^ bi | |
def clear_bit(x, i): | |
bi = ~(0b1 << i) | |
return x & bi | |
# more on topic: https://stackoverflow.com/questions/8898807/pythonic-way-to-iterate-over-bits-of-integer | |
def check_bits_set(x): | |
bit = 1 | |
bits = [] | |
while x >= bit: | |
if x & bit: | |
bits.append(bit) | |
bit <<= 1 | |
return bits |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment