ROTATE-BYTE
Function ROTATE-BYTE

Syntax:

rotate-byte count bytespec integer => result-integer

Arguments and Values:

count---an integer.

bytespec---a byte specifier.

integer---an integer.

result-integer---an integer.

Description:

Rotates a field of bits within integer; specifically, returns an integer that contains the bits of integer rotated count times leftwards within the byte specified by bytespec, and elsewhere contains the bits of integer.

Examples:

(rotate-byte 3 (byte 32 0) 3) => 24
(rotate-byte 3 (byte 5 5) 3) => 3
(rotate-byte 6 (byte 8 0) -3) => -129

Side Effects: None.

Affected By: None.

Exceptional Situations: None.

See Also:

byte, dpb, ldb

Reference implementation:

(defun rotate-byte (count bytespec integer)
  (let ((size (byte-size bytespec)))
    (when (= size 0)
      (return-from rotate-byte integer))
    (let ((count (mod count size)))
      (labels ((rotate-byte-from-0 (count size integer)
                 (let ((bytespec (byte size 0)))
                   (if (> count 0)
                       (logior (ldb bytespec (ash integer count))
                               (ldb bytespec (ash integer (- count size))))
                       (logior (ldb bytespec (ash integer count))
                               (ldb bytespec (ash integer (+ count size))))))))
        (dpb (rotate-byte-from-0 count size (ldb bytespec integer))
             bytespec
             integer)))))

[Peter Scott] SBCL's SB-ROTATE-BYTE contrib module implements this efficiently.