Lisp HUG Maillist Archive

Re: Is there a built-in way to decode/encode IEEE754 float number?

from somewhere on comp.lang.lisp:

;; Originally by Pascal Bourguignon.  Thanks to ivan4th
;; (~ivan_iv@nat-msk-01.ti.ru) for correcting an off-by-1.
(defmacro gen-ieee-encoding (name type exponent-bits mantissa-bits)
  `(progn
    (defun ,(intern (format nil "~A-TO-IEEE-754" name))  (float)
      (multiple-value-bind (mantissa exponent sign)
          (integer-decode-float float)
        (dpb (if (minusp sign) 1 0)
             (byte 1 ,(1- (+ exponent-bits mantissa-bits)))
             (dpb (+ ,(+ (- (expt 2 (1- exponent-bits)) 2) mantissa-bits)
                     exponent)
                  (byte ,exponent-bits ,(1- mantissa-bits))
                  (ldb (byte ,(1- mantissa-bits) 0) mantissa)))))
    (defun ,(intern (format nil "IEEE-754-TO-~A" name))  (ieee)
      (let ((aval (scale-float (coerce
                                (dpb 1 (byte 1 ,(1- mantissa-bits))
                                     (ldb (byte ,(1- mantissa-bits) 0) ieee))
                                ,type)
                               (- (ldb (byte ,exponent-bits ,(1- mantissa-bits))
                                       ieee)
                                  ,(1- (expt 2 (1- exponent-bits)))
                                  ,(1- mantissa-bits)))))
        (if (zerop (ldb (byte 1 ,(1- (+ exponent-bits mantissa-bits))) ieee))
            aval
            (- aval))))))

(gen-ieee-encoding float-32 'single-float 8 24)
(gen-ieee-encoding float-64 'double-float 11 53)

-russ

----- Original Message ----
From: Chun Tian (binghe) <binghe.lisp@gmail.com>
To: lisp-hug@lispworks.com
Sent: Tuesday, October 16, 2007 10:05:34 PM
Subject: Is there a built-in way to decode/encode IEEE754 float number?


Hi, Dear LispWorks Users

I'm trying to (re-)implement SNMP protocol [1], some part need encode a
single-float number into bytes which follow IEEE754 spec, and decode
these bytes.

I think maybe I needn't implement IEE754 by myself if LispWorks store
single-float number in the same format, am I right?
is there any built-in function or method to do this? Only for LispWorks
is OK.

Thanks.

Chun Tian (binghe)

[1] cl-net-snmp, a pure snmp package.
http://common-lisp.net/project/cl-net-snmp/







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