bitwise-bit-field(3scm) Scheme Programmer's Manual bitwise-bit-field(3scm)

bitwise-bit-field, fxbit-field - bit field extract

(import (rnrs))                     ;R6RS
(import (rnrs arithmetic bitwise))  ;R6RS
(import (rnrs arithmetic fixnums))  ;R6RS

(bitwise-bit-field ei start end)
(fxbit-field fx start end)

Returns the number represented by the bits at the positions from start (inclusive) to end (exclusive), which is the result of the following computation:
;; bitwise-bit-field
(let ((mask (bitwise-not
             (bitwise-arithmetic-shift-left -1 end))))
  (bitwise-arithmetic-shift-right (bitwise-and ei mask)
                                  start))
;; fxbit-field
(let ((mask (fxnot
             (fxarithmetic-shift-left -1 end))))
  (fxarithmetic-shift-right (fxand fx mask)
                            start))

Returns a single exact integer object.

(fxbit-field #b10101111 4 8)
          => #b1010
(fxbit-field #b10101111 0 4)
          => #b1111

The operation implemented by these procedures shows up when several fields are encoded in a single integer. A typical example is the code in a Scheme implementation that parses binary IEEE 754 floating point. This pattern also appears often in binary file formats, network protocols, machine code, encryption and much more.

These procedures are new in R6RS. SRFI-151 has the generic procedure under the name bit-field.

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. The arguments start and end must be non-negative and start must be less than or equal to end. The fxbit-field procedure requires that all arguments are fixnums.

bitwise-arithmetic-shift(3scm), bitwise-and(3scm)

R6RS

This page is part of the scheme-manpages project. It includes materials from the RnRS documents. More information can be found at https://weinholt.se/scheme/manpages/.

2021-03-11