UnderwareDESIGN

PlayBASIC => Resources => Source Codes => Topic started by: kevin on November 25, 2016, 05:54:06 PM

Title: Float to Fixed Point Conversion
Post by: kevin on November 25, 2016, 05:54:06 PM
  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

[pbcode]



   ; 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
                  

[/pbcode]