aboutsummaryrefslogtreecommitdiffstats
path: root/bits.py
diff options
context:
space:
mode:
Diffstat (limited to 'bits.py')
-rw-r--r--bits.py8
1 files changed, 7 insertions, 1 deletions
diff --git a/bits.py b/bits.py
index b3409da..b8cf441 100644
--- a/bits.py
+++ b/bits.py
@@ -1,3 +1,5 @@
+empty = (0, 0)
+
def u(num, bits):
""" parse an unsigned integer into a bitfield.
@@ -83,7 +85,7 @@ def concat(*parts):
size += psize
return (val, size)
-def slice(bits, hi, lo):
+def slice(bits, hi, lo, allow_empty=False):
""" slice a bitfield given hi and lo bit indices.
>>> slice((0x7f, 8), 7, 4)
@@ -105,6 +107,8 @@ def slice(bits, hi, lo):
Traceback (most recent call last):
...
ValueError: cant slice reverse range
+ >>> slice((0xf, 4), 2, 3, allow_empty=True)
+ (0, 0)
>>> slice((0xf, 4), 3, -1)
Traceback (most recent call last):
...
@@ -113,6 +117,8 @@ def slice(bits, hi, lo):
(val, size) = bits
if hi < lo:
+ if allow_empty:
+ return empty
raise ValueError("cant slice reverse range")
elif lo < 0 or hi >= size:
raise ValueError("slice [{}:{}] out of range ({} bit value)".format(hi, lo, size))