Ron schreef:
>
> Hi,
>
> Anyone have a routine to convert a hex string to a float?
> Like these:
> B6FBEB3A = -0.000007507766895287204
> 3C5D2104 = 0.01349664106965065
>
> Find lots of vb code, but those use copymem functions.
>
> Thanks in advance!
>
To answer my own question:

I ended up with this so far:

PUBLIC SUB Main()

  PRINT HexToFloat("3C5D2104")
  PRINT HexToFloat("B6FBEB3A")

END

PUBLIC FUNCTION HexToFloat(sHex AS String) AS Float

  DIM sTemp AS String
  DIM iSign, iExponent AS Integer
  DIM fTemp, fMant, fResult AS Float

  PRINT "Value = " & sHex
  ' calculate sign
  sTemp = Mid(sHex, 1, 2)
  fTemp = Val("&H" & sTemp) AND &H80
  iSign = IIf(fTemp = 128, -1, 1)
  PRINT "Sign = " & iSign

  ' calculate exponent
  sTemp = Mid(sHex, 1, 3)
  fTemp = Val("&H" & sTemp) AND &H7F8
  iExponent = fTemp / 2 ^ 3 - 127
  PRINT "Exponent = " & iExponent

  ' calculate mantissa
  sTemp = Mid(sHex, 3, 6)
  fTemp = Val("&H" & sTemp) AND &H7FFFFF
  fMant = (fTemp / 2 ^ 23) + 1
  PRINT "Mantissa = " & fMant

  fResult = iSign * fMant * 2 ^ iExponent

  RETURN fResult

END

Value = 3C5D2104
Sign = 1
Exponent = -7
Mantissa = 1.727570056915

Result: 0.01349664107

Value = B6FBEB3A
Sign = -1
Exponent = -18
Mantissa = 1.968116044998

Result: -7.507766895287E-6

Regards,
Ron_2nd


------------------------------------------------------------------------------
SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada.
The future of the web can't happen without you.  Join us at MIX09 to help
pave the way to the Next Web now. Learn more and register at
http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/
_______________________________________________
Gambas-user mailing list
Gambas-user@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/gambas-user

Reply via email to