Skip to content

Instantly share code, notes, and snippets.

@lordsutch
Created July 25, 2019 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lordsutch/7f360d8b1bfbd200d92e982d7ac1b483 to your computer and use it in GitHub Desktop.
Save lordsutch/7f360d8b1bfbd200d92e982d7ac1b483 to your computer and use it in GitHub Desktop.
Bitmask testing routine for Python 3.6+
# Copyright (C) 2019 Chris Lawrence
# You may freely modify, copy, and reuse this software under the terms of the MIT License.
def test_bitmask(value: int, mask: str) -> bool:
mask = mask.replace("_", "")
testval: int = 1
for bit in reversed(mask):
if bit == '1' and not (value & testval):
return False
elif bit == '0' and (value & testval):
return False
elif bit != "x":
raise ValueError('Invalid bitmask character: '+bit)
testval <<= 1
return True
assert( test_bitmask(0x80, '1xxx_xxxx') == True )
assert( test_bitmask(0x3f, '0xx1_xxxx') == True )
assert( test_bitmask(0x3f, '0xx1_xxx0') == False )
assert( test_bitmask(0xff, '0xx1_xxx0') == True ) # Should fail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment