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

1 Answer

0 votes
/*
    Combine two 32-bit values into one 64-bit value.

    - The high 32 bits are shifted left by 32 positions.
    - The low 32 bits are OR'ed in.

    PHP automatically promotes integers to 64-bit on 64-bit systems,
    so this works exactly like uint64_t in C++.
*/

/*
    Function that combines two 32-bit integers into a 64-bit integer
*/
function combine_two32bit(int $high, int $low): int {
    // Cast 'high' to 64-bit before shifting to avoid overflow
    $result = ((int)$high << 32) | $low;

    return $result;
}

/*
    Function that prints a 64-bit integer in hex with leading zeros
*/
function print_hex64(int $value): void {
    // "%016X" prints 16 hex digits (64 bits) with leading zeros
    printf("0x%016X\n", $value);
}

/*
    Main program logic
*/
$high = 0x11223344;   // Example high 32 bits
$low  = 0x55667788;   // Example low 32 bits

$combined = combine_two32bit($high, $low);

printf("High 32 bits: 0x%08X\n", $high);
printf("Low  32 bits: 0x%08X\n", $low);

echo "Combined 64-bit value: ";
print_hex64($combined);



/*
run:

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

*/

 



answered Jun 23 by avibootz
edited Jun 23 by avibootz

Related questions

...