def bitcount(num, length, value=1):
    """Counts the bits in num that are set to value (1 or 0, default 1)."""
    one_count = 0
    curr_length = length
    while num and curr_length:
        one_count += 1 & num
        num >>= 1
        curr_length -= 1
    if value:
        return one_count
    else:
        return length - one_count