[Gambas-user] Hex string to float

Ron ron at ...1740...
Sun Dec 14 23:21:44 CET 2008


Benoit Minisini wrote:
> On dimanche 14 décembre 2008, nando wrote:
>   
>> My apologies to all...I stand corrected for my mistake.
>> The i = &h3fd55555& converts hex to integer and is easiest to do it this
>> way. This method does performs as the original person wanted but is a waste
>> to do disk IO.  Perhaps a pipe, write the integer, read the single.
>> Although I haven't investigated, Gambas3 has pointers.
>> Copying 4B from a pointer to the 4B int to the 4B single will do it.
>> There are (older) versions of BASIC that had (something like) MKI$, MKS$,
>> MKD$ and counterparts (something like) CVI, CVS, CVD.  They took a string
>> and converted it to an Int Single Double.  No conversion happened because
>> the string was binary correct for the type. All it did was copy 2B, 4B 8B
>> from/to a numeric var to/from string.
>>  If Benoit were to incorporate these functions, it makes Gambas easily
>> perform IO of data types with ease to convert to native variables.
>> Thanks,
>> -Fernando
>>
>>     
>
> Yeh, this is planed.
>
> Anyway, you can do these conversion in Gambas 2 (and 3) this way:
>
> DIM sSrc AS String
> DIM eDst AS Float
> DIM pPtr AS Pointer
>
> pPtr = Alloc(8)
> WRITE #pPtr, sSrc, 8
> READ #pPtr, eDst
> Free(pPtr)
>
> But beware with the endianness!
>
>   

I'm not sure about who's float this thread is about at this moment, or 
if I use these routines false, but these calculations do not output a 
correct result for my need (converting a 8char lenght hex string to a 
ieee float http://steve.hollasch.net/cgindex/coding/ieeefloat.html , my 
original routine does, thought could maybe use some optimizations.

It's now down to:

PUBLIC FUNCTION HexToFloat(sHex AS String) AS Float

  DIM sTemp AS String
  DIM iSign AS Integer
  DIM fExponent, fMant AS Float

  ' sign
  iSign = IIf((Val("&H" & Mid(sHex, 1, 2)) AND &H80) = 128, -1, 1)
  ' exponent
  fExponent = (Val("&H" & Mid(sHex, 1, 3)) AND &H7F8) / 2 ^ 3 - 127
  ' mantissa
  fMant = (Val("&H" & Mid(sHex, 3, 6)) AND &H7FFFFF) / 2 ^ 23 + 1

  RETURN iSign * fMant * 2 ^ fExponent

END

Regards,
Ron_2nd




More information about the User mailing list