1;;;; bitwise-60 - SRFI-60 procedures without SRFI-33 analogues, renamed2;;; Copyright (C) 1991, 1993, 2001, 2003, 2005 Aubrey Jaffer3;4;Permission to copy this software, to modify it, to redistribute it,5;to distribute modified versions, and to use it for any purpose is6;granted, subject to the following restrictions and understandings.7;8;1. Any copy made of this software must include this copyright notice9;in full.10;11;2. I have made no warranty or representation that the operation of12;this software will be error-free, and I am under no obligation to13;provide any services, by way of maintenance, update, or otherwise.14;15;3. In conjunction with products arising from the use of this16;material, there shall be no use of my name in any advertising,17;promotional, or sales literature without prior written consent in18;each case.1920(define (bit-field-rotate n count start end)21 (define width (- end start))22 (set! count (modulo count width))23 (let ((mask (bitwise-not (arithmetic-shift -1 width))))24 (define zn (bitwise-and mask (arithmetic-shift n (- start))))25 (bitwise-ior (arithmetic-shift26 (bitwise-ior (bitwise-and mask (arithmetic-shift zn count))27 (arithmetic-shift zn (- count width)))28 start)29 (bitwise-and (bitwise-not (arithmetic-shift mask start)) n))))3031(define (bit-reverse k n)32 (do ((m (if (negative? n) (bitwise-not n) n) (arithmetic-shift m -1))33 (k (+ -1 k) (+ -1 k))34 (rvs 0 (bitwise-ior (arithmetic-shift rvs 1) (bitwise-and 1 m))))35 ((negative? k) (if (negative? n) (bitwise-not rvs) rvs))))363738(define (bit-field-reverse n start end)39 (define width (- end start))40 (let ((mask (bitwise-not (arithmetic-shift -1 width))))41 (define zn (bitwise-and mask (arithmetic-shift n (- start))))42 (bitwise-ior (arithmetic-shift (bit-reverse width zn) start)43 (bitwise-and (bitwise-not (arithmetic-shift mask start)) n))))4445(define (copy-bit index to bool)46 (if bool47 (bitwise-ior to (arithmetic-shift 1 index))48 (bitwise-and to (bitwise-not (arithmetic-shift 1 index)))))4950(define (bits->list k . len)51 (if (null? len)52 (do ((k k (arithmetic-shift k -1))53 (lst '() (cons (odd? k) lst)))54 ((<= k 0) (reverse lst)))55 (do ((idx (+ -1 (car len)) (+ -1 idx))56 (k k (arithmetic-shift k -1))57 (lst '() (cons (odd? k) lst)))58 ((negative? idx) (reverse lst)))))5960(define (list->bits bools)61 (do ((bs (reverse bools) (cdr bs))62 (acc 0 (+ acc acc (if (car bs) 1 0))))63 ((null? bs) acc)))6465(define (bits . bools)66 (list->bits bools))6768(define (bitwise-if mask n0 n1)69 (bitwise-ior (bitwise-and mask n0)70 (bitwise-and (bitwise-not mask) n1)))