VB.Net - 将多字节十六进制值转换为十进制
问题描述:
如何将两个单独的字节值(十六进制)转换为表示十六进制值连接的十进制值?举例来说,如果我有VB.Net - 将多字节十六进制值转换为十进制
Dim byte1 As Byte = &H99
Dim byte2 As Byte = &H99
' I want the decimal representation of the hex value "9999"
' (byte1.ToString + byte2.ToString) which should be "39321"
目前我使用下面的代码:
Dim decVal as integer
decVal = Val("&H" + Hex$(byte1).ToString + Hex$(byte2).ToString)
然而,当我用这个,值(decVal)出来为 “-26215”
我在这里做了什么错误的转换?
答
尝试以下操作:
decVal = byte1 * 256 + byte2
你的问题是,当你调用瓦尔(” & H9999" ),如果你使用CInt("&H9999")
或Integer.Parse("9999", System.Globalization.NumberStyles.HexNumber)
你(至少在这种情况下)得到正确的答案
如果你看一下输出:
decVal = Val("&H9999")
Console.WriteLine(decVal.ToString("X"))
你FFFF9999
我不知道为什么发生这种情况,但我认为这是一个理由不使用Val函数解析十六进制字符串
答
@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