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

1 Answer

0 votes
/*
    Combine two u32 values into one u64.

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

/// Combines two 32‑bit integers (`high` and `low`) into a single 64‑bit integer.
///
/// Explanation:
/// - `high` is cast to `u64` so it can be shifted safely.
/// - Shifting left by 32 moves it into the upper half of the 64‑bit value.
/// - `low` is also cast to `u64` and OR'ed into the lower half.
fn combine_two_32bit(high: u32, low: u32) -> u64 {
    (high as u64) << 32 | (low as u64)
}

/// Prints a u64 value in uppercase hexadecimal with leading zeros.
fn print_hex64(value: u64) {
    println!("0x{:016X}", value);
}

fn main() {
    let high: u32 = 0x11223344; // Example high 32 bits
    let low:  u32 = 0x55667788; // Example low 32 bits

    let combined = combine_two_32bit(high, low);

    println!("High 32 bits: 0x{:08X}", high);
    println!("Low  32 bits: 0x{:08X}", low);

    print!("Combined 64-bit value: ");
    print_hex64(combined);
}


/*
run:

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

*/

 



answered 8 hours ago by avibootz

Related questions

...