Skip to content

Instantly share code, notes, and snippets.

Created December 13, 2012 13:02
Show Gist options
  • Save anonymous/4276255 to your computer and use it in GitHub Desktop.
Save anonymous/4276255 to your computer and use it in GitHub Desktop.
Bitwise manipulation
def testBit(int_type, offset):
""" testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one. """
mask = 1 << offset
return(int_type & mask)
def setBit(int_type, offset):
""" setBit() returns an integer with the bit at 'offset' set to 1. """"
mask = 1 << offset
return(int_type | mask)
def clearBit(int_type, offset):
""" clearBit() returns an integer with the bit at 'offset' cleared."""
mask = ~(1 << offset)
return(int_type & mask)
def toggleBit(int_type, offset):
""" toggleBit() returns an integer with the bit at 'offset' inverted, 0 -> 1 and 1 -> 0."""
mask = 1 << offset
return(int_type ^ mask)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment