@Patrick麦当劳有这样做的一个很好的内联的方式,如果那是什么你正在寻找,然后我建议使用它。但我无法拒绝不给你提供过于复杂但跨平台和扩展的版本。有一点需要注意,您需要转换big-endian mode中的字节,这是一个非常重要的主题,以了解您是否在使用字节。
下面的两个函数都接受一个参数数组并执行转换,但有两种不同的方式。一个处理任意大的字节数组(仅限平台限制),另一个使用读取字节数组的内置转换器类。
再一次,让我强调一下“过于复杂”的部分。
Private Shared Function ConvertBytes2(ByVal ParamArray bytes() As Byte) As UInt32
''//Reverse the array order
Dim NewBytes = bytes.Reverse().ToList().ToArray()
''//Our return value
Dim Dec As UInt32 = 0
''//Temporary value for bit shifting
Dim T As UInt32
''//Loop through the bytes from left to right
For I = (NewBytes.Count - 1) To 0 Step -1
''//Grab the byte
T = NewBytes(I)
''//Shift it and add to our return value
Dec += T << (8 * I)
Next
Return Dec
End Function
Private Shared Function ConvertBytes1(ByVal ParamArray bytes() As Byte) As UInt32
''//We want to read the bytes in big-endian order but BitConverter works in little-endian mode on most Windows systems (but not all) so convert if needed
Dim NewBytes() As Byte
If BitConverter.IsLittleEndian Then
NewBytes = bytes.Reverse().ToList().ToArray()
Else
NewBytes = bytes
End If
''//Our return value
Dim Dec As UInt32
''//BitConverter can return UIn16, 32 or 64, we're only supporting 16 and 32 below
If NewBytes.Count = 2 Then
Dec = BitConverter.ToUInt16(NewBytes, 0)
ElseIf NewBytes.Count = 4 Then
Dec = BitConverter.ToUInt32(NewBytes, 0)
Else
''//Invalid number of bytes sent
Throw New ArgumentOutOfRangeException("bytes")
End If
Return Dec
End Function
Dim Byte1 As Byte = &HA
Dim Byte2 As Byte = &H99
''//&h0A99 = 2,713
Trace.WriteLine(ConvertBytes1(Byte1, Byte2))
Trace.WriteLine(ConvertBytes2(Byte1, Byte2))
所以我想,我想知道如果有人可以向我解释为什么我的方法不起作用?在我提交的情况下,什么原因会导致返回负值? – GregH 2011-04-26 00:15:59