News:

Building a 3D Ray Tracer  By stevmjon

Main Menu

Float to Fixed Point Conversion

Started by kevin, November 25, 2016, 05:54:06 PM

Previous topic - Next topic

kevin

  Float to Fixed Point  Conversion
 
   The code bellows shows one way that you can convert floats into fixed point integers and back again.  The conversion allows the user to select the bit range of the fixed point value, making it lossy, the less bits the more loss..  

    Run in Debug Mode (f7)  outputs to console

PlayBASIC Code: [Select]
   ; number of bits then fixed point version needs
Bits = 16


For Value#= -1000 to 1000 step 10


#print " Input:"+Str$(Value#)



; lossy conversion to 16bit fixed point
one_divided_by_Value_Integer = (1 / Value#) * (2^Bits)



; Clean high bits of fixed point version.
FixedPointValue = ((one_divided_by_Value_Integer << (32-Bits)) >> (32-Bits))



#print " Fixed:"+Str$(FixedPointValue) + " Hex$ "+ hex$(FixedPointValue)




; convert back to 32bit float..
; -----------------------------------------------


; Extend Sign fixed point version to 32bit integer
FixedPointValue |= (FixedPointValue >> (Bits -1)) * ($ffffffff << (32-Bits))

Result# = (2^Bits)/float(FixedPointValue)


#print "Output:"+Str$(result#)

#print ""

next

sync
waitkey