def bits_to_intervals(bits):
    """ Converts bit numbers to bit intervals.

:returns: list of tuples: [(bitoffset_0, bitsize_0), ...]
    """

    if not bits:
        return []

    bit_numbers = sorted(bits)
    result = []
    bitoffset = prev_bit = bit_numbers[0]
    bitsize = 1

    for bit in bit_numbers[1:]:
        if bit - prev_bit == 1:
            bitsize += 1
        else:
            result.append((bitoffset, bitsize))
            bitoffset = bit
            bitsize = 1

        prev_bit = bit

    result.append((bitoffset, bitsize))
    return result