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

1 Answer

0 votes
package main

import (
    "fmt"
)

// combineTwo32bit combines two uint32 values (high and low)
// into one uint64 value.
//
// Explanation:
// - The high 32 bits are shifted left by 32 positions.
// - The low 32 bits are OR'ed into the lower half.
// - Casting to uint64 before shifting is required to avoid overflow.
func combineTwo32bit(high, low uint32) uint64 {
    return (uint64(high) << 32) | uint64(low)
}

// printHex64 prints a uint64 value in uppercase hexadecimal
// with a leading "0x" prefix.
func printHex64(v uint64) {
    fmt.Printf("0x%016X\n", v)
}

func main() {
    // Example values
    high := uint32(0x11223344)
    low := uint32(0x55667788)

    combined := combineTwo32bit(high, low)

    fmt.Printf("High 32 bits: 0x%08X\n", high)
    fmt.Printf("Low  32 bits: 0x%08X\n", low)

    fmt.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

...