Parsing a sequence of bits out of a bit field
This is not the kind of thing you should loop for. Just calculate a mask:

def parse_out_bits(bit_field: int, start_index: int, end_index: int) -&gt; int:
    mask = (1 &lt;&lt; (end_index - start_index + 1)) - 1
    return (bit_field &gt;&gt; start_index) &amp; mask


In English:


If you're getting bits 5-7, that's 3 bits
2^3 == 8, - 1 = 7 (or 111 in binary - that is your mask)
Shift the field right by 5 to put the bits of interest in the least-significant position
And-mask them to get the result.