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

1 Answer

0 votes
/*
    Combine two 32‑bit unsigned integers into one 64‑bit unsigned integer.

    - The high 32 bits are shifted left by 32 positions.
    - The low 32 bits are OR'ed into the lower half.
*/

import Foundation

// Function that combines two UInt32 values into a single UInt64.
//
// Explanation:
// - Convert `high` to UInt64 so it can be shifted safely.
// - Shift it left by 32 bits to place it in the upper half.
// - Convert `low` to UInt64 and OR it into the lower half.
func combineTwo32bit(high: UInt32, low: UInt32) -> UInt64 {
    return (UInt64(high) << 32) | UInt64(low)
}

// Function that prints a UInt64 in uppercase hexadecimal
// with leading zeros.
func printHex64(_ value: UInt64) {
    print(String(format: "0x%016lX", value))
}

func main() {
    let high: UInt32 = 0x11223344   // Example high 32 bits
    let low:  UInt32 = 0x55667788   // Example low 32 bits

    let combined = combineTwo32bit(high: high, low: low)

    print(String(format: "High 32 bits: 0x%08X", high))
    print(String(format: "Low  32 bits: 0x%08X", low))

    print("Combined 64-bit value: ", terminator: "")
    printHex64(combined)
}

main()


/*
run:

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

*/

 



answered 7 hours ago by avibootz

Related questions

...