Lisp HUG Maillist Archive

single or double float from byte array

How do you create a single or double float from a Lisp array of bytes?

	Thanks, Joel

--------------------------------------------------------------------------
- for hire: mac osx device driver ninja, kernel extensions and usb drivers
---------------------+------------+---------------------------------------
http://wagerlabs.com | @wagerlabs | http://www.linkedin.com/in/joelreymont
---------------------+------------+---------------------------------------


Re: single or double float from byte array

Joel Reymont wrote:
> How do you create a single or double float from a Lisp array of bytes?
> 

There may be an easier method (i.e., using undocumented functions), but 
this seems to work for me assuming IEEE 754 on a little-endian arch:

(defun unsigned-bytes-to-float (bytes)
   #-ieee-floating-point (error "fixme")
   (let ((ft (ecase (length bytes)
               (4 :lisp-single-float)
               (8 :lisp-double-float))))
     (fli:with-dynamic-foreign-objects
         ((x (:unsigned :byte)
             :initial-contents (coerce bytes 'list)
             :nelems (length bytes)))
       (fli:with-coerced-pointer
           (y :type ft) x
         (fli:dereference y)))))

CL-USER 361 > (= pi (unsigned-bytes-to-float (reverse #(#x40 #x09 #x21 
#xfb #x54 #x44 #x2d #x18))))
T


Mike


Re: single or double float from byte array

Hi Joel,

On 26 sept. 2011, at 21:32, Joel Reymont wrote:

> How do you create a single or double float from a Lisp array of bytes?

You could try the ieee-floats library:

http://common-lisp.net/project/ieee-floats/


Works well for me.


Best Regards,
Cam


Updated at: 2020-12-10 08:37 UTC