-
-
Save javiermon/4276262 to your computer and use it in GitHub Desktop.
handy functions to work with 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
# (unset) mask = 0xff - (1 << offset) if (nibble == 'lower') else 0xff - (4 << (4 - offset)); operation = & | |
# (set) mask = 1 << offset if (nibble == 'lower') else 4 << (4 - offset); operation = | | |
# | |
# (read) result = (current_values & 0x0F) if (nibble == 'lower') else (current_values & 0xF0) >> 4 | |
# (write) mask = (offset - 1) & 0xf0 if (nibble == 'lower') else 4 << (offset - 1) & 0x0f; operation = | | |
def getNibbles(int_type): | |
""" getNibbles() returns the byte nibbles for a given integer (upper, lower) """ | |
return((int_type & 0xF0) >> 4, (int_type & 0x0F)) | |
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