BitConverter.ToInt64溢出异常

时间:2016-11-19 11:15:50

标签: .net vb.net bitconverter

我在第一步(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

1 个答案:

答案 0 :(得分:2)

您的代码中有两个错误。

  1. 您允许BitConverter将您的字节转换为Int64值,您尝试将其插入UInt64集合中。这可能会导致 OverflowException ,因为UInt64不能代表负值。

    您需要将BitConverter产生的类型与列表存储的类型进行匹配,以便执行以下任一操作(两者都不是!):

    • BitConverter.ToInt64(…)替换为BitConverter.ToUInt64(…)
    • 声明Dim UintList As New List(Of Int64)而不是List(Of UInt64)
  2. 您的数组的长度(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