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

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

/*
    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.
*/
class Program
{
    static int RemoveBitsAndShift(int number, int[] positions)
    {
        // Copy and sort positions descending
        int[] sorted = (int[])positions.Clone();
        Array.Sort(sorted);
        Array.Reverse(sorted);

        int result = number;

        foreach (int pos in sorted) {
            int leftPart  = result >> (pos + 1);          // bits above removed bit
            int rightPart = result & ((1 << pos) - 1);    // bits below removed bit

            result = (leftPart << pos) | rightPart;       // merge
        }

        return result;
    }

    /*
        printBinary(n)
        --------------
        Prints a 32-bit binary representation of an integer.
    */
    static void PrintBinary(int n)
    {
        string binary = Convert.ToString(n, 2).PadLeft(32, '0');

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

        Console.WriteLine(binary);
    }

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

        Console.WriteLine("Original number in binary:");
        PrintBinary(number);

        int result = RemoveBitsAndShift(number, positions);

        Console.WriteLine();
        Console.WriteLine("Number after removing bits {1, 3, 7} and shifting remaining bits:");
        PrintBinary(result);

        Console.WriteLine();
        Console.WriteLine("Result 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

...