Güven Acar Güven Acar - 21 days ago 7
Vb.net Question

BitConverter.ToInt64 OverflowException

I had error "OverflowException" at first step (i=0). What is wrong in this code?

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

Answer

You have two errors in your code.

  1. You let BitConverter convert your bytes to Int64 values, which you try to insert into a UInt64 collection. This can cause OverflowException, because UInt64 cannot represent negative values.

    You need to match up the type of what BitConverter produces with what your list stores, so do either of the following (both not both!):

    • Replace BitConverter.ToInt64(…) with BitConverter.ToUInt64(…).
    • Declare Dim UintList As New List(Of Int64) instead of as List(Of UInt64).
  2. Your array has a length (75 bytes) that is not divisible by 8, which will cause a ArgumentException on the last loop iteration. BitConverter.ToInt64 expects that there will be at least 8 bytes available from the specified starting offset i. However, once it gets to offset 72, there are only 4 bytes left, which is not enough to produce a Int64.

    Therefore, you need to check whether there are enough bytes left to convert:

    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