How to combine two 32-bit values into one 64-bit value Pascal

1 Answer

0 votes
program Combine32bitTo64bit;

{

    UInt32 = unsigned 32-bit integer
    UInt64 = unsigned 64-bit integer

    Combine two UInt32 values into one UInt64.

    The usual pattern:
        result := (UInt64(high) shl 32) or low;

    Explanation:
    - The 'high' 32-bit value is cast to UInt64 so it can be shifted safely.
    - Shifting left by 32 moves it into the upper half of the 64‑bit integer.
    - The 'low' 32-bit value is OR'ed in to fill the lower half.
}

uses
  SysUtils;

// Function that combines two 32-bit integers into a 64-bit integer
function CombineUInt32(high, low: UInt32): UInt64;
var
  result64: UInt64;
begin
  // Cast 'high' to UInt64 to avoid overflow before shifting
  result64 := (UInt64(high) shl 32) or low;

  CombineUInt32 := result64;
end;

// Function that prints a UInt64 in hex with leading zeros
procedure PrintHex64(value: UInt64);
begin
  WriteLn('0x', IntToHex(value, 16));
end;

var
  high, low: UInt32;
  combined: UInt64;

begin
  high := $11223344;   // Example high 32 bits
  low  := $55667788;   // Example low 32 bits

  combined := CombineUInt32(high, low);

  WriteLn('High 32 bits: 0x', IntToHex(high, 8));
  WriteLn('Low  32 bits: 0x', IntToHex(low, 8));

  Write('Combined 64-bit value: ');
  PrintHex64(combined);
end.



{
run:

High 32 bits: 0x11223344
Low  32 bits: 0x55667788
Combined 64-bit value: 0x1122334455667788

}

 



answered 11 hours ago by avibootz
edited 10 hours ago by avibootz
...