[iolib-devel] receiving signed integers

Stelian Ionescu sionescu at common-lisp.net
Tue Jun 3 07:43:38 UTC 2008


On Mon, Jun 02, 2008 at 08:45:37AM -0700, elliott wrote:
>Hi,
>
>I've reached a point in writing some code where I must read a singed 
>32bit integer from a socket.  I've been using 
>NET.SOCKETS:RECEIVE-FROM to read '(unsigned-byte 8) values.  Can 
>anyone suggest a good library (or alternate method) to help with the 
>conversion?

I'm afraid that you'll have to do manual conversion for the moment until
I'll add the proper routines to write into arrays other than
'(unsigned-byte 8). Here's a piece of code that can do just that,
albeit slowly.

(defun aref-32 (ub8-array &optional (offset 0) (endianess :little-endian) (type :signed))
  (let ((value
         (ecase endianess
           (:big-endian
              (+ (ash (aref ub8-array offset) 24)
                 (ash (aref ub8-array (+ 1 offset)) 16)
                 (ash (aref ub8-array (+ 2 offset)) 8)
                 (aref ub8-array (+ 3 offset))))
           (:little-endian
              (+ (aref ub8-array offset)
                 (ash (aref ub8-array (+ 1 offset)) 8)
                 (ash (aref ub8-array (+ 2 offset)) 16)
                 (ash (aref ub8-array (+ 3 offset)) 24))))))
    (if (and (eq :signed type) (logbitp 31 value))
      (lognot (logxor value #xFFFFFFFF))
      value)))

HU> (aref-32 #(255 0 0 0) 0 :big-endian :unsigned)
4278190080
HU> (aref-32 #(255 0 0 0) 0 :little-endian :unsigned)
255
HU> (aref-32 #(255 0 0 0) 0 :big-endian :signed)
-16777216
HU> (aref-32 #(255 0 0 0) 0 :little-endian :signed)
255

-- 
Stelian Ionescu a.k.a. fe[nl]ix
Quidquid latine dictum sit, altum videtur.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <https://mailman.common-lisp.net/pipermail/iolib-devel/attachments/20080603/2d7682e3/attachment.sig>


More information about the iolib-devel mailing list