Hi,
in a software written in VB2015 ( I must modify ) I found a Function that converts an input Int32 value into an UInt32 value.
The original purpose was to use an SQL INT Field ( 4 Bytes ) to store an UInt32 value ( 4 Bytes ).
This is the original Function "ConvertToUInt32" :
Public Function ConvertToUInt32(ByVal ValInt As Int32,
ByRef ValUInt32Ret As UInt32,
ByRef pErrorMsg As String) As Boolean
Try
Dim ValUInt32 As UInt32 = 0
Dim ArrBytes As Byte() = BitConverter.GetBytes(ValInt)
ValUInt32 = ArrBytes(3)
ValUInt32 <<= 24
ValUInt32Ret = ValUInt32
ValUInt32 = ArrBytes(2)
ValUInt32 <<= 16
ValUInt32Ret += ValUInt32
ValUInt32 = ArrBytes(1)
ValUInt32 <<= 8
ValUInt32Ret += ValUInt32
ValUInt32Ret += ArrBytes(0)
Return True
Catch ex As Exception
pErrorMsg = "ERROR ConvertToUInt32 Array Bytes : " & ex.Message
Return False
End Try
End Function
And this is the Function "GetUInt32FromInt32" I wrote myself to replace the first one :
Public Function GetUInt32FromInt32(ByVal pInt32 As Int32) As UInt32
If pInt32 >= 0 Then
Return Convert.ToUInt32(pInt32)
Else
Return Convert.ToUInt32(UInt32.MaxValue + pInt32 + 1)
End If
End Function
I've made some tests with this code :
Dim SBTest As New System.Text.StringBuilder
Dim valueInt32 As Int32 = Convert.ToInt32(txt_valueint32.Text)
Dim valueUInt32 As UInt32
Dim errorMsg As String = String.Empty
SBTest.AppendLine("valueInt32 = " & valueInt32.ToString)
If ConvertToUInt32(valueInt32,
valueUInt32,
errorMsg) = True Then
SBTest.AppendLine("ConvertToUInt32() valueUInt32 = " & valueUInt32.ToString)
Else
SBTest.AppendLine("Conversion FAILED for " & valueInt32.ToString & " : " & errorMsg)
End If
valueUInt32 = GetUInt32FromInt32(valueInt32)
SBTest.AppendLine("GetUInt32FromInt32() valueUInt32 = " & valueUInt32.ToString)
Clipboard.SetText(SBTest.ToString)
And the results are always the same for both :
valueInt32 = 0
ConvertToUInt32() valueUInt32 = 0
GetUInt32FromInt32() valueUInt32 = 0
valueInt32 = 254
ConvertToUInt32() valueUInt32 = 254
GetUInt32FromInt32() valueUInt32 = 254
valueInt32 = -1
ConvertToUInt32() valueUInt32 = 4294967295
GetUInt32FromInt32() valueUInt32 = 4294967295
valueInt32 = -254
ConvertToUInt32() valueUInt32 = 4294967042
GetUInt32FromInt32() valueUInt32 = 4294967042
valueInt32 = 2147483647 ( Int32 MAX )
ConvertToUInt32() valueUInt32 = 2147483647
GetUInt32FromInt32() valueUInt32 = 2147483647
valueInt32 = -2147483648 ( Int32 MIN )
ConvertToUInt32() valueUInt32 = 2147483648
GetUInt32FromInt32() valueUInt32 = 2147483648
The questions are :
- Are these two Functions equivalent in your opinion ?
- Do you think I could get the same operation with another simpler method ? How ?
Thaks to anyone able to help.