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

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.

    TypeScript uses JavaScript's BigInt type to safely handle 64-bit integers.
*/

// ------------------------------------------------------------
// Function that combines two 32-bit integers into a 64-bit BigInt
// ------------------------------------------------------------
function combineTwo32bit(high: number, low: number): bigint {
    // Convert both values to BigInt before shifting
    const high64: bigint = BigInt(high);
    const low64: bigint = BigInt(low);

    // Shift the high part left by 32 bits and OR with the low part
    const result: bigint = (high64 << 32n) | low64;

    return result;
}

// ------------------------------------------------------------
// Function that prints a 64-bit BigInt in hex with leading zeros
// ------------------------------------------------------------
function printHex64(value: bigint): void {
    // Convert to hex string and pad to 16 bytes (64 bits)
    const hex: string = value.toString(16).toUpperCase().padStart(16, "0");
    console.log("0x" + hex);
}

// ------------------------------------------------------------
// Main program logic
// ------------------------------------------------------------
function main(): void {
    const high: number = 0x11223344;   // Example high 32 bits
    const low: number  = 0x55667788;   // Example low 32 bits

    const combined: bigint = combineTwo32bit(high, low);

    console.log("High 32 bits: 0x" + high.toString(16).toUpperCase().padStart(8, "0"));
    console.log("Low  32 bits: 0x" + low.toString(16).toUpperCase().padStart(8, "0"));

    // Replaced process.stdout.write with console.log
    console.log("Combined 64-bit value:");
    printHex64(combined);
}

main();


/*
run:

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

*/

 



answered 10 hours ago by avibootz

Related questions

...