How to combine two 32-bit values into one 64-bit value in VB.NET

1 Answer

0 votes
Imports System

' ***************************************************************
'   VB.NET Example:
'   Combine two 32-bit unsigned integers into one 64-bit unsigned integer.
'
'
'   - The high 32 bits are shifted left by 32 positions.
'   - The low 32 bits are OR'ed into the lower half.
'
'   This program includes:
'       • A function to combine two UInt32 values
'       • A function to print UInt64 in hex
'       • A demonstration in Main()
' ***************************************************************

Module Program

    ' ---------------------------------------------------------------
    ' Function: Combine two 32-bit values into one 64-bit value
    ' ---------------------------------------------------------------
    Function CombineUInt32(high As UInt32, low As UInt32) As UInt64
        ' Convert "high" to UInt64 before shifting to avoid overflow.
        ' In VB.NET, CULng converts to UInt64 when the target type is UInt64.
        Dim result As UInt64 = (CULng(high) << 32) Or low
        Return result
    End Function

    ' ---------------------------------------------------------------
    ' Function: Print a UInt64 value in hexadecimal with leading zeros
    ' ---------------------------------------------------------------
    Sub PrintHex64(value As UInt64)
        ' "X16" formats as 16 hex digits with leading zeros (for 64 bits)
        Console.WriteLine("0x" & value.ToString("X16"))
    End Sub

    ' ---------------------------------------------------------------
    ' Main Program Entry Point
    ' ---------------------------------------------------------------
    Sub Main()
        ' Example values
        Dim high As UInt32 = &H11223344UI   ' High 32 bits
        Dim low As UInt32  = &H55667788UI   ' Low 32 bits

        ' Combine them
        Dim combined As UInt64 = CombineUInt32(high, low)

        ' Display results
        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)
    End Sub

End Module



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

 



answered 2 hours ago by avibootz
edited 1 hour ago by avibootz

Related questions

...