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

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.
*/

object Combine32To64 {

  // Function that combines two 32‑bit integers into a 64‑bit integer.
  //
  // Explanation:
  // - Convert both values to Long (Scala's 64‑bit signed integer).
  // - Shift the high part left by 32 bits.
  // - OR the low part into the lower 32 bits.
  def combineTwo32bit(high: Int, low: Int): Long = {
    (high.toLong << 32) | (low.toLong & 0xFFFFFFFFL)
  }

  // Function that prints a 64‑bit value in uppercase hexadecimal
  // with leading zeros.
  def printHex64(value: Long): Unit = {
    println(f"0x$value%016X")
  }

  def main(args: Array[String]): Unit = {
    val high: Int = 0x11223344   // Example high 32 bits
    val low:  Int = 0x55667788   // Example low 32 bits

    val combined: Long = combineTwo32bit(high, low)

    println(f"High 32 bits: 0x$high%08X")
    println(f"Low  32 bits: 0x$low%08X")

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



/*
run:

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

*/

 



answered 8 hours ago by avibootz

Related questions

...