Re: Reading Binary Files: Best Practices?



Madhu <enometh@xxxxxxxx> wrote:

* (Bob Felts) <1irwxg6.14vwqbobbbm70N%wrf3@xxxxxxxxxxxxxxx> :
Wrote on Sun, 14 Dec 2008 00:38:13 -0500:

| (defun sign-ui16 (n)
| (if (zerop (ldb (byte 1 15) n))
| n
| (- (1+ (logxor #xffff n)))))
|
| If the sign-bit is zero, return the number. If it's set, return -(~n +
| 1). (Note: lognot doesn't work - it has to be logxor).
|
| Any suggestions on a better way to do this?

Here is general code from Pascal Bourguignon

(defun unsigned-to-signed/2-complement (x width)
(declare (integer x width))
(let ((maxpos+1 (expt 2 (1- width))))
(if (< x maxpos+1) x (- x (* 2 maxpos+1)))))

Most of the code I've seen which reads signed 16bit words is along these
lines: declare the variable to be an unsigned-byte 16, check and
subtract 65536, or just return n.

This does not address how n was read from the external file, endianness
in which the file was stored. For parsing binary files I've been using
frodef's excellent

<URL:http://www.cs.uit.no/~frodef/sw/binary-types/>

(from even before PCL came out.) There you'd do

(read-binary 's16 stream)


Thanks. Excellent information.
.



Relevant Pages

  • Re: Reading Binary Files: Best Practices?
    ... | If the sign-bit is zero, ... Here is general code from Pascal Bourguignon ... (declare (integer x width)) ...
    (comp.lang.lisp)
  • Re: coding problem using salford FTN95
    ... values less than zero make no physical sense here. ... the code does not declare the types of any of its variables. ... the compilers implicit typing so that you will get an error message ... The program statement is supposed to ...
    (comp.lang.fortran)
  • Re: Base
    ... Moreover, if you only want to worry about typical machines, then the values ... but that would fail if the range of G_Int didn't include zero. ... Slightly less sloppy programmers would declare the counter as having the ...
    (comp.lang.ada)
  • Re: Numeric rounding not working?
    ... The data type decimal holds zero digits after the decimal point, ... declare @lat1 as float ...
    (microsoft.public.sqlserver.programming)
  • Re: which is better... SET or SELECT?
    ... FROM sysobjects ... SELECT @id -- Returns Zero ... > One important difference between SET and SELECT for variable assignment is> the behaviour when no rows are returned from the SELECT statement. ... > DECLARE @id INTEGER ...
    (microsoft.public.sqlserver.programming)