VB.NET Hexadecimal to Floating Point / Single (IEEE 754)
A post just came across the forum I frequent regarding Hexadecimal to Floating Point conversion. Strangely there appears to be no direct way to do this in .NET, and the solutions I found were pretty lame and tedious… so it became my mission to get it done the .NET way, and here is the result:
Private Function ConvertHexToSingle(ByVal hexValue As String) As Single
Try
Dim iInputIndex As Integer = 0
Dim iOutputIndex As Integer = 0
Dim bArray(3) As Byte
For iInputIndex = 0 To hexValue.Length - 1 Step 2
bArray(iOutputIndex) = Byte.Parse(hexValue.Chars(iInputIndex) & hexValue.Chars(iInputIndex + 1), Globalization.NumberStyles.HexNumber)
iOutputIndex += 1
Next
Array.Reverse(bArray)
Return BitConverter.ToSingle(bArray, 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 Function
ConvertHexToSingle("3C000000")
Even though this is just a rough example, it does work, and it can be expanded to support larger types (such as Double) with a couple of small mods.