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

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.

    JavaScript Numbers cannot safely hold 64-bit integers,
    so we use BigInt for correct 64-bit behavior.
*/

// ------------------------------------------------------------
// Function that combines two 32-bit integers into a 64-bit integer
// ------------------------------------------------------------
function combineTwo32bit(high, low) {
    // Convert to BigInt before shifting to avoid precision loss
    const high64 = BigInt(high);
    const low64  = BigInt(low);

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

    return result;
}

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

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

    const combined = 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"));

    process.stdout.write("Combined 64-bit value: ");
    printHex64(combined);
}

main();


/*
run:

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

*/

 



answered 12 hours ago by avibootz
edited 10 hours ago by avibootz

Related questions

...