How to remove a bit from a number and shift all bits to the right to fill the gap in Python

1 Answer

0 votes
# Removes the bit at the given position and shifts all higher bits right.
def remove_bit_and_shift(number, position):
    """
    Removes the bit at the given position and shifts all higher bits right.

    Example:
        number = 22 (10110)
        position = 2 (0 = LSB)

        Bits: 1 0 1 1 0
                  ^ remove this bit

        left  = bits above removed bit
        right = bits below removed bit

        result = (left << position) | right
    """
    left = number >> (position + 1)              # bits above removed bit
    right = number & ((1 << position) - 1)       # bits below removed bit
    return (left << position) | right            # merge shifted left + right


# Python binary printing using format() + zfill() + grouping
def print_binary(value):
    """
    Prints a 32-bit binary representation of an integer.
    Uses Python:
        format(value, 'b') → binary string
        zfill(32) → pad to 32 bits
        grouping into 4-bit chunks for readability
    """
    binary = format(value, 'b').zfill(32)
    grouped = " ".join(binary[i:i+4] for i in range(0, 32, 4))
    print(grouped)


def main():
    number = 22
    position = 2  # remove bit 2 (0 = LSB)

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

    result = remove_bit_and_shift(number, position)

    print("\nNumber after removing bit", position, "and shifting remaining bits:")
    print_binary(result)

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


if __name__ == "__main__":
    main()



"""
run:

Original number in binary:
0000 0000 0000 0000 0000 0000 0001 0110

Number after removing bit 2 and shifting remaining bits:
0000 0000 0000 0000 0000 0000 0000 1010

Result as integer: 10

"""

 



answered Jun 24 by avibootz
edited Jun 24 by avibootz

Related questions

...