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

1 Answer

0 votes
using System;

/*
    Combine two uint32 values into one uint64.

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

    - The high 32 bits are shifted left by 32 positions.
    - The low 32 bits are OR'ed in.
*/

class Program
{
    // ------------------------------------------------------------
    // Function that combines two 32-bit integers into a 64-bit integer
    // ------------------------------------------------------------
    static ulong combineTwo32bit(uint high, uint low)
    {
        // Cast 'high' to ulong to avoid overflow before shifting
        ulong result = ((ulong)high << 32) | low;

        return result;
    }

    // ------------------------------------------------------------
    // Function that prints a uint64 in hex with leading zeros
    // ------------------------------------------------------------
    static void PrintHex64(ulong value)
    {
        Console.WriteLine("0x" + value.ToString("X16"));
    }

    static void Main()
    {
        uint high = 0x11223344;   // Example high 32 bits
        uint low  = 0x55667788;   // Example low 32 bits

        ulong combined = combineTwo32bit(high, low);

        Console.WriteLine("High 32 bits: 0x" + high.ToString("X8"));
        Console.WriteLine("Low  32 bits: 0x" + low.ToString("X8"));

        Console.Write("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
edited Jun 23 by avibootz

Related questions

...