Created
February 9, 2014 22:41
-
-
Save IanConnolly/8907171 to your computer and use it in GitHub Desktop.
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 get_val_from_binary_range(high_bit, low_bit, int_type): | |
''' | |
Returns the numeric value of the bits bounded by low_bit and high_bit in the int_type param | |
low_bit becomes the new value's zeroth bit | |
''' | |
val = 0 | |
cur_bit = high_bit | |
while (cur_bit >= low_bit): | |
val = val << 1 | |
if test_bit(int_type, cur_bit) != 0: | |
val = set_bit(val, 0) | |
cur_bit = cur_bit - 1 | |
return val | |
# Below from https://wiki.python.org/moin/BitManipulation | |
# First two needed, last two for completeness | |
def test_bit(int_type, offset): | |
mask = 1 << offset | |
return (int_type & mask) | |
def set_bit(int_type, offset): | |
mask = 1 << offset | |
return (int_type | mask) | |
def clear_bit(int_type, offset): | |
mask = ~(1 << offset) | |
return (int_type & mask) | |
def flip_bit(int_type, offset): | |
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