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

1 Answer

0 votes
#include <stdio.h>
#include <stdint.h>

/*
    Combine two uint32_t values into one uint64_t.

    The usual pattern:
        uint64_t result = ( (uint64_t)high << 32 ) | low;

    Explanation:
    - The 'high' 32-bit value is cast to uint64_t so it can be shifted safely.
    - Shifting left by 32 moves it into the upper half of the 64‑bit integer.
    - The 'low' 32-bit value is OR'ed in to fill the lower half.
*/

// Function that combines two 32-bit integers into a 64-bit integer
uint64_t combine_uint32(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) {
    printf("0x%016llX\n", (unsigned long long)value);
}

int main() {
    uint32_t high = 0x11223344;   // Example high 32 bits
    uint32_t low  = 0x55667788;   // Example low 32 bits

    uint64_t combined = combine_uint32(high, low);

    printf("High 32 bits: 0x%08X\n", high);
    printf("Low  32 bits: 0x%08X\n", low);

    printf("Combined 64-bit value: ");
    print_hex64(combined);

    return 0;
}


/*
run:

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

*/

 



answered 12 hours ago by avibootz
edited 12 hours ago by avibootz
...