def bitrev(inval, nbits):
    """This function bit-reverses the given value "inval" with the number of
    bits, "nbits".    ----  R. Ramachandran, 10-Nov-97, nfra.
    python version ----  H. Chen   Modified 2014
    2020-07-21 speedup --- R. Elkins (texadactyl)

    Args:
      inval: number to be bit-reversed
      nbits: The length of inval in bits. If user only wants the bit-reverse of a certain amount of bits of
    inval, nbits is the amount of bits to be reversed counting from the least significant (rightmost)
    bit. Any bits beyond this length will not be reversed and will be truncated from the result.

    Returns:
      : the bit-reverse of inval. If there are more significant bits beyond nbits, they are truncated.

    """
    if nbits <= 1:
        ibitr = inval
    else:
        ifact = 2**(nbits - 1)
        k = inval
        ibitr = 0 if (1 & k == 0) else ifact
        for i in range(2, nbits+1):
            k = k >> 1
            ifact = ifact >> 1
            if 1 & k:
                ibitr += ifact
    return ibitr