Created
July 25, 2019 16:57
-
-
Save lordsutch/7f360d8b1bfbd200d92e982d7ac1b483 to your computer and use it in GitHub Desktop.
Bitmask testing routine for Python 3.6+
This file contains hidden or 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
# 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