The less-familiar parts of Lisp for beginners — byte

On to more obscure Lisp commands.  The byte command is used to generate a bitrange specifier.  This can then be passed to some other function like ldb or dpb so that manipulations can be made to individual bits within an integer.  This is perhaps best shown with an example:

CL-USER> (let ((b1 (byte 16 0))
               (b2 (byte 16 1)))
           (format t "Byte 16 0:  #x~X~%" (dpb #x01234567 b1 0))
           (format t "Byte 16 1:  #x~X~%" (dpb #x01234567 b2 0))
           (format t "Byte 16 1 / 2:  #x~X~%" (/ (dpb #x01234567 b2 0) 2)))
Byte 16 0:  #x4567
Byte 16 1:  #x8ACE
Byte 16 1 / 2:  #x4567

What this sequence says is that we define b1 to be an interval of 16 bits, shifted 0 bits from the right (and so enclosing the 16 least-significant bits in the integer).  We define b2 to be an interval of 16 bits, but shifted by 1 bit from the right, so it encloses the 16 bits immediately above the least-significant bit.  We’ve then used dpb to deposit the least significant 16 bits of the hexadecimal literal #x01234567 into the integer 0.  With b1, it inserts into the least significant bits of the number 0, so the effect is to copy #x4567 into the least-significant position of a number that otherwise has all bits zero.  With b2, the insertion is one bit to the left, producing a new sequence #x8ACE which is twice #x4567, because it is shifted one bit to the left.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.