Skip to content

Instantly share code, notes, and snippets.

@IanConnolly
Created February 9, 2014 22:41
Show Gist options
  • Save IanConnolly/8907171 to your computer and use it in GitHub Desktop.
Save IanConnolly/8907171 to your computer and use it in GitHub Desktop.
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