How to remove multiple bits from a number and shift the remaining bits right to fill the gaps in Python

1 Answer

0 votes
"""
    remove_bits_and_shift(number, positions)
    ----------------------------------------
    Removes multiple bit positions from a number and shifts the remaining bits
    right to fill the gaps.

    Important:
        Bits must be removed from highest → lowest position.
        Otherwise earlier removals shift the positions of later ones.
"""
def remove_bits_and_shift(number, positions):
    # Sort positions descending
    sorted_positions = sorted(positions, reverse=True)

    result = number

    for pos in sorted_positions:
        left  = result >> (pos + 1)          # bits above removed bit
        right = result & ((1 << pos) - 1)    # bits below removed bit

        result = (left << pos) | right       # merge

    return result


"""
    print_binary(n)
    ---------------
    Prints a 32-bit binary representation of an integer.
"""
def print_binary(n):
    binary = format(n, "032b")               # 32‑bit padded binary string
    grouped = " ".join(binary[i:i+4] for i in range(0, 32, 4))
    print(grouped)


# Main program
number = 1234                 # 0000 0000 0000 0000 0000 0100 1101 0010
positions = [1, 3, 7]         # remove bits 1, 3, 7 (0 = LSB)

print("Original number in binary:")
print_binary(number)

result = remove_bits_and_shift(number, positions)

print("\nNumber after removing bits {1, 3, 7} and shifting remaining bits:")
print_binary(result)

print("\nResult as integer:", result)



"""
run:

Original number in binary:
0000 0000 0000 0000 0000 0100 1101 0010

Number after removing bits {1, 3, 7} and shifting remaining bits:
0000 0000 0000 0000 0000 0000 1001 0100

Result as integer: 148

"""

 



answered 1 day ago by avibootz

Related questions

...