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

1 Answer

0 votes
program CopyBitsPascal;

{
    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 }
function ToBinary(x: QWord): string;
var
    s: string;
begin
    if x = 0 then
    begin
        ToBinary := '0';
        Exit;
    end;

    s := '';
    while x > 0 do
    begin
        if (x and 1) = 1 then
            s := '1' + s
        else
            s := '0' + s;
        x := x shr 1;
    end;

    ToBinary := s;
end;

{ Copy bits from M into N between bit positions [i, j] }
function CopyBits(N, M: QWord; i, j: Integer): QWord;
var
    length: Integer;
    mask: QWord;
    N_cleared: QWord;
    M_shifted: QWord;
begin
    if (i < 0) or (j < 0) or (i > j) or (j >= 63) then
    begin
        Writeln('Error: Invalid bit range');
        Halt(1);
    end;

    length := j - i + 1;

    { Mask for bits i..j }
    mask := ((QWord(1) shl length) - 1) shl i;

    { Clear bits i..j in N }
    N_cleared := N and (not mask);

    { Take only the needed bits from M and shift into place }
    M_shifted := (M and ((QWord(1) shl length) - 1)) shl i;

    CopyBits := N_cleared or M_shifted;
end;

var
    N, M, R: QWord;
begin
    {
        N:      100 011111 00
        M:          110011
        Result: 100 110011 00
    }

    N := %10001111100;   { Pascal binary literal }
    M := %110011;

    R := CopyBits(N, M, 2, 7);

    Writeln('N:      ', ToBinary(N));
    Writeln('M:      ', ToBinary(M));
    Writeln('Result: ', ToBinary(R));
end.



{
OUTPUT:

N:      10001111100
M:      110011
Result: 10011001100

}

 



answered Mar 30 by avibootz

Related questions

...