def reverse24(x, k=24):
    """reverses order of bits 0,...,k-1 of an integer. Default is k=24.

    If any bits apart form bit 0,...,k-1 are set, an execption is raised.
    """
    if x & -(1 << k):
        raise ValueError("Too high bits are set for bit reversal")
    return sum( ((x >> (k-i-1)) & 1) << i  for  i in range(k) )