This is a piece of Visual Basic code which gives an exception, FormatException.
Suppose my hex value, variable hexValue, is 424E0A78. The code works properly. The moment hexValue gets a value (say) 424EA78, this exception occurs:
The supplied hex value is either empty or in an incorrect format. Use the following format: 00000000
Is there a solution?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim hexValue As String = "424E0A78"
Dim iInputIndex As Integer = 0
Dim iOutputIndex As Integer = 0
Dim bArray(3) As Byte 'creating an array
Dim rnum As Integer
Dim rArray(3) As Byte
Dim rSingle As Single
Dim rSingle1 As Single
Dim rSingle2 As Single
Dim rStr As Integer
Dim rnewArray(3) As Byte ' variables
Dim rnum2, rnum3 As Integer 'variables
Dim rstr2, rstr3 As String
'For iInputIndex = 0 To hexValue.Length - 1 Step 2
For iInputIndex = 0 To hexValue.Length - 1 Step 2
'rnum3 = hexValue.Chars(iInputIndex) * 16
'REjina code starts
rStr = 0
rstr2 = hexValue.Chars(iInputIndex)
If (rstr2 = "A") Then
rstr2 = 10
ElseIf (rstr2 = "B") Then
rstr2 = 11
ElseIf (rstr2 = "C") Then
rstr2 = 12
ElseIf (rstr2 = "D") Then
rstr2 = 13
ElseIf (rstr2 = "E") Then
rstr2 = 14
ElseIf (rstr2 = "F") Then
rstr2 = 15
End If
rStr = Val(rstr2) * 16
'Second rejina conversion
rstr2 = hexValue.Chars(iInputIndex + 1)
If (rstr2 = "A") Then
rstr2 = 10
ElseIf (rstr2 = "B") Then
rstr2 = 11
ElseIf (rstr2 = "C") Then
rstr2 = 12
ElseIf (rstr2 = "D") Then
rstr2 = 13
ElseIf (rstr2 = "E") Then
rstr2 = 14
ElseIf (rstr2 = "F") Then
rstr2 = 15
End If
rStr = rStr + Val(rstr2)
'rstr2 = hexValue.Chars(iInputIndex + 1)
rnewArray(iOutputIndex) = rStr
'rejina code ends
'rArray(iOutputIndex) = Byte.Parse(hexValue.Chars(iInputIndex) & hexValue.Chars(iInputIndex + 1), Globalization.NumberStyles.HexNumber)
'bArray(iOutputIndex) = Convert.ToByte(hexValue.Chars(iInputIndex))
iOutputIndex += 1
Next
'Array.Reverse(rArray)
'rejina code starts
Array.Reverse(rnewArray)
'rejina code ends
'Array.Reverse(bArray)
'rSingle = BitConverter.ToSingle(rArray, 0)
'rejina code starts
rSingle1 = BitConverter.ToSingle(rnewArray, 0)
'rejina code ends
'rSingle2 = BitConverter.ToSingle(bArray, 0)
MessageBox.Show(rSingle1)
'Return BitConverter.ToSingle(rnewArray, 0)
Catch ex As Exception
Throw New FormatException("The supplied hex value is either empty or in an incorrect format. Use the following format: 00000000", ex)
End Try
End Sub
If the input string had an odd (i.e. not even) length then you’ll get an array index out of bounds exception on the line:
…which is most likely what you’re experiencing here.