Skip to content

Instantly share code, notes, and snippets.

@labianchin
Last active April 28, 2018 13:51
Show Gist options
  • Save labianchin/8090635 to your computer and use it in GitHub Desktop.
Save labianchin/8090635 to your computer and use it in GitHub Desktop.
Bit Set, Bit Get
#!/usr/bin/python
def getbit(n, i):
"""
>>> getbit(4, 0)
False
>>> getbit(4, 1)
False
>>> getbit(4, 2)
True
>>> getbit(7, 0)
True
>>> getbit(7, 1)
True
>>> getbit(7, 2)
True
>>> getbit(7, 3)
False
"""
return n & (1 << i) > 0
def setbit(n, i, st):
"""
>>> setbit(4, 0, True)
5
>>> setbit(4, 1, True)
6
>>> setbit(4, 2, True)
4
>>> setbit(7, 0, False)
6
>>> setbit(7, 1, False)
5
>>> setbit(7, 2, False)
3
>>> setbit(7, 3, False)
7
>>> setbit(7, 3, True)
15
"""
if (st):
return n | (1<<i)
else:
return n & ~(1<<i)
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment