bitwise-rotate-bit-field, fxrotate-bit-field - bitwise rotate left
(import (rnrs)) ;R6RS
(import (rnrs arithmetic bitwise)) ;R6RS
(import (rnrs arithmetic fixnums)) ;R6RS
(bitwise-rotate-bit-field n start end count)
(fxrotate-bit-field n start end count)
Returns the result of cyclically permuting in n the bits at positions
from start (inclusive) to end (exclusive) by bits towards
the more significant bits.
The following are reference implementations from R6RS.
;; bitwise-rotate-bit-field
(let ((width (- end start)))
(if (positive? width)
(let* ((count (mod count width))
(field0
(bitwise-bit-field n start end))
(field1 (bitwise-arithmetic-shift-left
field0 count))
(field2 (bitwise-arithmetic-shift-right
field0
(- width count)))
(field (bitwise-ior field1 field2)))
(bitwise-copy-bit-field n start end field))
n))
;; fxrotate-bit-field
(let ((width (fx- end start)))
(fxcopy-bit-field n start end
(fxior
(fxarithmetic-shift-left
(fxbit-field n start (fx- end count))
count)
(fxarithmetic-shift-right
(fxbit-field n start end)
(fx- width count)))))
Returns a single value; an exact integer.
(fxrotate-bit-field #x1234 4 12 4) => #x1324
Bitwise rotation is a common operation in cryptography.
These procedures are unique to R6RS. Similar alternatives can be found in
SRFI-60 and SRFI-151.
These procedures can raise exceptions with the following condition types:
- &assertion (R6RS)
- The wrong number of arguments was passed or an argument was outside its
domain. In particular, all arguments must be exact integers, start,
end and count must be non-negative, and start must be
less than or equal to end.
- For the fixnum variant there are further restrictions. All arguments must
be fixnums, and start, end and count must be less
than the implementation's fixnum width, and count must be less than
or equal to end-start.
Many processor instruction set architectures have an integer rotate instruction.
R6RS was the first Scheme report to standardize this operation. Previously
SRFI-60 had slightly different bit-field-rotate procedure. Early Scheme
running on MacLISP had access to the rot procedure that rotated a whole
36-bit fixnum by some amount.