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

1 Answer

0 votes
public class RemoveBitAndShift {

    // Removes the bit at the given position and shifts all higher bits right.
    public static int removeBitAndShift(int number, int position) {
        /**
            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
        */

        int left  = number >> (position + 1);            // bits above removed bit
        int right = number & ((1 << position) - 1);      // bits below removed bit

        return (left << position) | right;               // merge shifted left + right
    }

    // Java binary printing using String.format + padding
    public static void printBinary(int value) {
        // Convert to binary, pad to 32 bits with zeros
        String binary = String.format("%32s",
                Integer.toBinaryString(value))
                .replace(' ', '0');

        // Print with spacing every 4 bits
        for (int i = 0; i < 32; i++) {
            System.out.print(binary.charAt(i));
            if ((i + 1) % 4 == 0) System.out.print(" ");
        }
    }

    public static void main(String[] args) {
        int number = 22;
        int position = 2; // remove bit 2 (0 = LSB)

        System.out.println("Original number in binary:");
        printBinary(number);

        int result = removeBitAndShift(number, position);

        System.out.println("\n\nNumber after removing bit " + position +
                           " and shifting remaining bits:");
        printBinary(result);

        System.out.println("\n\nResult as integer: " + result);
    }
}


/*
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 23 by avibootz
edited Jun 24 by avibootz

Related questions

...