def num2bits(num, length=0):
    """
    Convert a number to an array of bits of the give length
    """
    if length and num.bit_length() > length:
        raise ValueError('Number does not fit in bits')
    bits = []
    while num:
        bits.insert(0, num & 1)
        num = num >> 1
    return [0] * (length - len(bits)) + bits