How to copy bits from M into N (numbers) between bit positions i and j (edge‑case‑safe) in C#

1 Answer

0 votes
using System;

class CopyBitsProgram
{
    /*
        Handles edge cases:
        - Validates i and j
        - Prevents undefined behavior from shifting by ≥ 64 bits
        - Masks M so only the required bits are copied
    */

    // Convert unsigned 64‑bit integer to binary string without leading zeros
    static string ToBinary(ulong x) {
        if (x == 0UL)
            return "0";

        string s = "";

        while (x != 0UL) {
            s = ((x & 1UL) == 1UL ? "1" : "0") + s;
            x >>= 1;
        }

        return s;
    }

    // Copy bits from M into N between bit positions [i, j]
    static ulong CopyBits(ulong N, ulong M, int i, int j) {
        if (i < 0 || j < 0 || i > j || j >= 63)
            throw new ArgumentException("Invalid bit range");

        int length = j - i + 1;

        // Mask for bits i..j
        ulong mask = ((1UL << length) - 1UL) << i;

        // Clear bits i..j in N
        ulong N_cleared = N & ~mask;

        // Take only the needed bits from M and shift into place
        ulong M_shifted = (M & ((1UL << length) - 1UL)) << i;

        return N_cleared | M_shifted;
    }

    static void Main()
    {
        /*
            N:      100 011111 00
            M:          110011
            Result: 100 110011 00
        */

        ulong N = 0b10001111100UL;
        ulong M = 0b110011UL;

        ulong result = CopyBits(N, M, 2, 7);

        Console.WriteLine("N:      " + ToBinary(N));
        Console.WriteLine("M:      " + ToBinary(M));
        Console.WriteLine("Result: " + ToBinary(result));
    }
}


/*
OUTPUT:

N:      10001111100
M:      110011
Result: 10011001100

*/

 



answered Mar 30 by avibootz

Related questions

...