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

1 Answer

0 votes
#include <iostream>
#include <cstdint>
 
/*
    Combine two uint32_t values into one uint64_t.
 
    The usual pattern:
        uint64_t result = ( (uint64_t)high << 32 ) | low;
 
    - The high 32 bits are shifted left by 32 positions.
    - The low 32 bits are OR'ed in.
*/
 
// Function that combines two 32-bit integers into a 64-bit integer
uint64_t combine_two_32bit(uint32_t high, uint32_t low) {
    // Cast 'high' to uint64_t to avoid overflow before shifting
    uint64_t result = ( (uint64_t)high << 32 ) | low;
     
    return result;
}
 
// Function that prints a uint64_t in hex with leading zeros
void print_hex64(uint64_t value) {
    std::cout << "0x"
              << std::hex 
              << std::uppercase 
              << value 
              << std::dec 
              << std::endl;
}
 
int main() {
    uint32_t high = 0x11223344;   // Example high 32 bits
    uint32_t low  = 0x55667788;   // Example low 32 bits
 
    uint64_t combined = combine_two_32bit(high, low);
 
    std::cout << "High 32 bits: 0x" << std::hex << high << std::endl;
    std::cout << "Low  32 bits: 0x" << std::hex << low  << std::endl;
 
    std::cout << "Combined 64-bit value: ";
    print_hex64(combined);
}
 
 
/*
run:
 
High 32 bits: 0x11223344
Low  32 bits: 0x55667788
Combined 64-bit value: 0x1122334455667788
 
*/

 



answered Jun 22 by avibootz
edited Jun 23 by avibootz

Related questions

...