User Tools

Site Tools


Converting Between Single Precision and Double Precision Floats In Basic

The Armmites and Picomites use double precision floats. When interfacing some devices they will return the 32 bits that represent a single precision float. In the Micromites which use single precision you can just POKE the 32 bits into the memory occupied by a float and then access the value by using the variable.

The MMBasic devices using double precision expect you to POKE 64 bits, but you only have 32. See this post for how to manipulate the bits so you end up with 64 bits in the format expected by double precision.

This TBS post

Functions in MMBasic

The functions below, contributed by various TBS members, are extracted from the TBS thread.

Function to convert from single to double precision

Use this to manipulate 32 bits received from a device formatted as a single precision float to covert them to a double precision float.

'you pass in the 4 hex bytes of the single-precision number as a string
'The function returns the double precision float
function CDBL(s$)
  local w%,c%,d%,e%,o%,a!  
  If Left$(s$,2)<>"&H" Then s$="&H"+s$
  Poke word Peek(varaddr w%),Val(s$) 'store the single precision floating point
  c%=(w% And &H80000000)<<32 'get the sign bit
  d%=(w% And &h7FFFFF)<<29 'get the mantissa
  e%=(((w% And &H7f800000)>>23)-127+1023)<<52 'get the exponent and convert
  o%=(c% Or d% Or e%)
  Poke integer Peek(varaddr a!),o% 'put the answer into a double
end function
Function to convert from double to single precision

Use this to manipulate a double precision float to extract 32 bits formatted as single precision needed to send data to a device that expects only 32bits.

'you pass in the 8 byte double-precision float number
'The function returns a hex string containing the 32bits for the single precision float. 
Function CSGL$(a!)
  Local out$="", sgl$=""
  sgl$= Bin2str$(single, a!, BIG)
  For n=1 To 4
  CSGL$ = out$
End Function
mmbasic/converting_a_single_precision_float_to_double_in_basic.txt · Last modified: 2024/06/23 20:08 by gerry