vb.netcastingoverflowexception

Cannot cast int32 to int16. Int16 type value is too large or too small


I want to cast an Int32 value to Int16 value. Data lost when casting is not a problem to me. But a System.OverflowException says the Int16 type value is too large or too small.

Dim num As Int32 = &HFFFFFFF
Dim num2 As Int16 = Convert.ToInt16(num)
Debug.WriteLine(num.ToString("X4"))
Debug.WriteLine(num2.ToString("X4"))

If I want to cast an Int32 &HFFFFFFF to &HFFFF so what should I do.

Any help would be appreciated.


Solution

  • I think, as I said in my comment, that your casting is invalid because int16 has maxValue and MinValue which your int32 obviously does not sit in between.

    Try the following to see your error more clearly:

     Debug.WriteLine(Int16.MaxValue.ToString)
     Debug.WriteLine(Int16.MinValue.ToString)
     Debug.WriteLine(num.ToString)
    

    enter image description here

    Your best workaround is to trim the last 4 F off your int32 whenever converting, if you still insist on doing it:

     Sub Main()
            Dim num As Int32 = &HFFFFFFF
            Dim num2 As Int16 = Convert.ToInt16(num.ToString("X8").Substring(num.ToString("X8").Length - 4, 4), 16)
            Debug.WriteLine(num.ToString("X4"))
            Debug.WriteLine(num2.ToString("X4"))
            Console.ReadLine()
        End Sub