Craig Gemmill's Blog

There is nothing more secure than an educated user!

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.

 

Comments

Ben said:

Thanks for the help.  Here it is in C#!

       private Single ConvertHexToSingle (string hexVal) {

           try {

               int i=0, j=0;

               byte[] bArray = new byte[4];

               for (i = 0; i <= hexVal.Length-1; i += 2) {

                   bArray[j] = Byte.Parse (hexVal[i].ToString() + hexVal[i + 1].ToString(), System.Globalization.NumberStyles.HexNumber);

                   j += 1;

               }

               Array.Reverse (bArray);

               Single s =  BitConverter.ToSingle (bArray, 0);

               return (s);

           } catch (Exception ex) {

               throw new FormatException ("The supplied hex value is either empty or in an incorrect format.  Use the " +

                   "following format: 00000000", ex);

           }

       }

# October 23, 2006 1:09 PM

David said:

How about ConvertSingletoHex

# December 15, 2006 3:51 AM

Sylvain Huot said:

Thanks for above code, it helped me.

Here's a little vb contribution:

   Private Function ConvertSingleToHex(ByVal SngValue As Single) As String

       Dim tmpBytes() As Byte

       Dim tmpHex As String = ""

       tmpBytes = BitConverter.GetBytes(SngValue)

       For b As Integer = tmpBytes.GetUpperBound(0) To 0 Step -1

           If Hex(tmpBytes(b)).Length = 1 Then tmpHex += "0" '0..F -> 00..0F

           tmpHex += Hex(tmpBytes(b))

       Next

       Return tmpHex

   End Function

# January 31, 2007 12:21 PM

Larry said:

Thanks, everybody, this was very helpful.

# July 25, 2007 3:13 PM

Valery(ru) said:

Thanks for code, it helps me with segy's file types

# October 19, 2007 1:46 AM

Taner Ozdas said:

Is any body know how to do above conversions as vb6 ?

# November 2, 2007 4:37 AM

Hans said:

Nice coding !

It helped me for sure. Can anyone do the vice versa.

that is 401.10 to hexadecimal conversion.

# December 19, 2007 11:40 PM

Ruiner333 said:

       static void Main(string[] args)

       {

           // Initial Value

           float num1 = 999999f;

           // Convert to IEEE 754

           uint num2 = BitConverter.ToUInt32(BitConverter.GetBytes(num1), 0);

           Console.WriteLine("{0} : {1}", num1, num2);

           // Hex representation

           byte[] byteArray = BitConverter.GetBytes(num1);

           Array.Reverse(byteArray);

           Console.WriteLine(BitConverter.ToString(byteArray).Replace("-", ""));

           // Convert back to float

           float num3 = BitConverter.ToSingle(BitConverter.GetBytes(num2), 0);

           Console.WriteLine(num3);

           Console.ReadKey();

       }

# February 25, 2008 9:47 PM

greg said:

hi all,i search for function for translate byte to real if you can help me... thanks

# March 3, 2008 10:54 AM

ravindran.VRK said:

hi all,

can you plz tell me the way how can we convert the Hex value to Float value using VB6.0

# July 23, 2008 8:12 AM

KNot said:

A little C# contribution…

private string ConvertSingleToHex(Single SngValue)

{

    string hexString = string.Empty;

    Byte[] tmpBytes = BitConverter.GetBytes(SngValue);            

    Array.Reverse(tmpBytes);

    hexString = HexEncoding.ToString(tmpBytes);

    return hexString;

}

# February 6, 2009 1:31 PM

VB_Noob_needs_help said:

As I'm a pretty beginner in VB.NET

I wanted to ask you guys if someone could

provide me a lil Float2Hex and Hex2Float Converter App?

Just buttons and textboxes.

I also would like to learn how to do it myself. so maybe one of you could tell me how to implement the upper snippet into a form.

Any help is appreciated.

thx in advance.

# March 3, 2009 1:39 PM

EC said:

How did you come up with that code?  I don't understand the code in the for loop can somebody explain?

# March 6, 2009 5:06 PM

Vinodh said:

Thanks Craig. this worked for me.

# April 29, 2009 11:50 AM

Aamir said:

caqn any one help me how to convert byte to single in vb6

# November 12, 2009 7:50 AM

Andrea said:

Hi. I used your code for convert Hexadecimal to Floating Point, but it doesnt work well for non integer numbers.

For example if I insert 4020H, doesnt convert to 2.5d however, the result is 2d

Please help me!

# June 21, 2010 2:57 PM

Najmul Hoda said:

Thanks It helped me alot

# July 15, 2010 5:48 AM

bitcoin said:

s4mgu2u qr7340i u3yp1uy oicf8fn hkt0ma6.

# September 17, 2011 5:04 PM

Adriano said:

BitConverter.ToSingle is also useful!

# January 16, 2012 3:46 PM

M.P.A.J. de Hoogh said:

Somewhat more efficient would be to eliminate the Reverse thing:

Private Function ConvertHexToSingle(ByVal hexValue As String) As Single

       Try

           Dim iOutputIndex As Integer = 0

           Dim bArray(3) As Byte

           For iInputIndex As Integer = 6 To 0 Step -2 ' comparing with 0 is faster

               bArray(iOutputIndex) = Byte.Parse(hexValue.Substring(iInputIndex,2), Globalization.NumberStyles.HexNumber)

               iOutputIndex += 1

           Next

           Return BitConverter.ToSingle(bArray, 0)

       Catch ex As Exception

       End Try

       Return Single.NaN ' something invalid was provided

   End Function

# March 28, 2012 10:24 AM

cheap oem software said:

tMAEvd I really enjoy the article. Want more.

# May 2, 2012 6:55 PM