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

1 Answer

0 votes
import java.util.Arrays;

/**
    removeBitsAndShift(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.
*/
public class Main {

    public static int removeBitsAndShift(int number, int[] positions) {

        // Sort positions descending
        int[] sorted = Arrays.copyOf(positions, positions.length);
        Arrays.sort(sorted);
        for (int i = 0; i < sorted.length / 2; i++) {
            int tmp = sorted[i];
            sorted[i] = sorted[sorted.length - 1 - i];
            sorted[sorted.length - 1 - i] = tmp;
        }

        int result = number;

        for (int pos : sorted) {
            int left  = result >> (pos + 1);          // bits above removed bit
            int right = result & ((1 << pos) - 1);    // bits below removed bit

            result = (left << pos) | right;           // merge
        }

        return result;
    }

    /**
        printBinary(n)
        --------------
        Prints a 32-bit binary representation of an integer.
    */
    public static void printBinary(int n) {
        String binary = String.format("%32s", Integer.toBinaryString(n))
                .replace(' ', '0');

        // Group into 4-bit chunks
        binary = binary.replaceAll("(.{4})", "$1 ");

        System.out.println(binary);
    }

    public static void main(String[] args) {

        int number = 1234;             // 0000 0000 0000 0000 0000 0100 1101 0010
        int[] positions = {1, 3, 7};   // remove bits 1, 3, 7 (0 = LSB)

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

        int result = removeBitsAndShift(number, positions);

        System.out.println("\nNumber after removing bits {1, 3, 7} and shifting remaining bits:");
        printBinary(result);

        System.out.println("\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

...