我在第一步(i = 0)遇到错误“OverflowException”。这段代码有什么问题?
Dim byteArray As Byte() = { _
0, 54, 101, 196, 255, 255, 255, 255, 0, 0, _
0, 0, 0, 0, 0, 0, 128, 0, 202, 154, _
59, 0, 0, 0, 0, 1, 0, 0, 0, 0, _
255, 255, 255, 255, 1, 0, 0, 255, 255, 255, _
255, 255, 255, 255, 127, 86, 85, 85, 85, 85, _
85, 255, 255, 170, 170, 170, 170, 170, 170, 0, _
0, 100, 167, 179, 182, 224, 13, 0, 0, 156, _
88, 76, 73, 31, 242}
Dim UintList As New List(Of UInt64)
For i As Integer = 0 To byteArray.Count - 1 Step 8
UintList.Add(BitConverter.ToInt64(byteArray, i))
Next
答案 0 :(得分:2)
您的代码中有两个错误。
您允许BitConverter
将您的字节转换为Int64
值,您尝试将其插入UInt64
集合中。这可能会导致 OverflowException
,因为UInt64
不能代表负值。
您需要将BitConverter
产生的类型与列表存储的类型进行匹配,以便执行以下任一操作(两者都不是!):
BitConverter.ToInt64(…)
替换为BitConverter.ToUInt64(…)
。Dim UintList As New List(Of Int64)
而不是List(Of UInt64)
。您的数组的长度(75个字节)不能被8整除,这会在最后一个循环迭代中产生 ArgumentException
。 BitConverter.ToInt64
期望指定的起始偏移量i
中至少有8个字节可用。但是,一旦它偏移72,只剩下4个字节,这不足以产生Int64
。
因此,您需要检查是否还有足够的字节进行转换:
For i As Integer = 0 To byteArray.Count - 1 Step 8
If i + 8 <= byteArray.Length Then
… ' enough bytes available to convert to a 64-bit integer
Else
… ' not enough bytes left to convert to a 64-bit integer
End
Next