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

1 Answer

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

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

fun combineTwo32bit(high: UInt, low: UInt): ULong {
    /*
        Steps:
        1. Convert `high` to ULong so it can be shifted safely.
        2. Shift it left by 32 bits to place it in the upper half.
        3. Convert `low` to ULong and OR it into the lower half.
    */
    return (high.toULong() shl 32) or low.toULong()
}

// Function that prints a 64‑bit value in uppercase hexadecimal
// with leading zeros.
//
// Note: String.format does not understand ULong directly,
// so we convert to Long first.
fun printHex64(value: ULong) {
    println("0x%016X".format(value.toLong()))
}

fun main() {
    val high: UInt = 0x11223344u   // Example high 32 bits
    val low:  UInt = 0x55667788u   // Example low 32 bits

    val combined: ULong = combineTwo32bit(high, low)

    // String.format also doesn't support UInt directly,
    // so we convert to Int for printing.
    println("High 32 bits: 0x%08X".format(high.toInt()))
    println("Low  32 bits: 0x%08X".format(low.toInt()))

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



/*
run:

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

*/

 



answered Jun 23 by avibootz

Related questions

...