From: ·········@atc.alcoa.com
Subject: Writing and reading binary files with CL
Date: 
Message-ID: <WATTON_JD.95Jun16144156@watson.atc.alcoa.com>
I have a problem in writing binary files. I need to write both
integers and floats to a binary file. The only lisp utility is
write-byte which only takes integers as input. How do I convert a
single-float to the IEEE equivalent 32bit integer so that I can write
the number?

For the reading of binary files the integers can be converted to
single-floats with the following:

(defvar *byte131* (byte 1 31))
(defvar *byte832* (byte 8 23))
(defvar *byte230* (byte 23 0))

(defun fix-to-float (num)
  (let ((sign (ldb *byte131* num))
	(expt (- (ldb *byte832* num) 127))
	(frac (ldb *byte230* num)))
    (format t "~a ~a ~a" sign expt frac)
    (cond ((or (< expt -126))
	   0.0)
	  ((> sign 0)
	   (- (scale-float (float (+ 8388608 frac) 1.0) (- expt 23))))
	  (t
	   (scale-float (float (+ 8388608 frac) 1.0) (- expt 23))))))

This works but I can't seem to reverse it for writing
purposes. Someone must know of a better way to write and read?

John D. Watton
Aluminum Company of America
Alcoa Technical Center
100 Technical Drive, Alcoa Center PA 15069
From: Barry Margolin
Subject: Re: Writing and reading binary files with CL
Date: 
Message-ID: <3s28e9$nus@tools.near.net>
In article <·······················@watson.atc.alcoa.com> ·········@atc.alcoa.com writes:
>(defun fix-to-float (num)
...
>This works but I can't seem to reverse it for writing
>purposes. Someone must know of a better way to write and read?

The opposite of SCALE-FLOAT is INTEGER-DECODE-FLOAT.  So you should be able
to write:

(defun float-to-fix (num)
  (multiple-value-bind (frac expt sign)
      (integer-decode-float num)
    (let ((result frac))
      (setf (ldb *byte832* result) expt)
      (when (minusp sign)
        (setf (ldb *byte131* result) 1)))))
-- 
Barry Margolin
BBN Planet Corporation, Cambridge, MA
······@{bbnplanet.com,near.net,nic.near.net}
Phone (617) 873-3126 - Fax (617) 873-5124