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

bitwise-first-bit-set, fxfirst-bit-set - first bit set in an integer

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

(bitwise-first-bit-set ei)
(fxfirst-bit-set fx)

Returns the index of the least significant 1 bit in the two's complement representation of the argument. If it is 0, then −1 is returned.

The argument to fxfirst-bit-set must be in the implementation's fixnum range.

Returns a single value; an exact integer.

(bitwise-first-bit-set 0)   =>  -1
(bitwise-first-bit-set 1)   =>  0
(bitwise-first-bit-set -4)  =>  2

These procedures have a variety of uses, e.g. for using integers to represent sets, and some bit-hacks.

Some CPUs have an instruction that is similar to this procedure, such as the BSF instruction in the x86 ISA. If it was instead defined by user code then it would be much slower.

The fixnum variant of this procedure works with the implementation-defined fixnum range.

This procedure can raise exceptions with the following condition types:
&assertion (R6RS)
The wrong number of arguments was passed or an argument was outside its domain.

bitwise-length(3scm)

R4RS, IEEE Scheme, R5RS, R6RS, R7RS, SRFI-60, SRFI-143, SRFI-151

These procedures are new in 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/.

2022-04-09