这是一段给出异常FormatException的 Visual Basic 代码。
假设我的十六进制值 variablehexValue
是 424E0A78。代码工作正常。当hexValue
得到一个值(比如)424EA78时,就会发生这个异常:
提供的十六进制值为空或格式不正确。使用以下格式:00000000
有解决办法吗?
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