srfi-151

Fork of the SRFI-151 reference implementation for CHICKEN

git clone https://git.8pit.net/srfi-151.git

 1;;;; bitwise-60 - SRFI-60 procedures without SRFI-33 analogues, renamed
 2;;; Copyright (C) 1991, 1993, 2001, 2003, 2005 Aubrey Jaffer
 3;
 4;Permission to copy this software, to modify it, to redistribute it,
 5;to distribute modified versions, and to use it for any purpose is
 6;granted, subject to the following restrictions and understandings.
 7;
 8;1.  Any copy made of this software must include this copyright notice
 9;in full.
10;
11;2.  I have made no warranty or representation that the operation of
12;this software will be error-free, and I am under no obligation to
13;provide any services, by way of maintenance, update, or otherwise.
14;
15;3.  In conjunction with products arising from the use of this
16;material, there shall be no use of my name in any advertising,
17;promotional, or sales literature without prior written consent in
18;each case.
19
20(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-shift
26             (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))))
30
31(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))))
36
37
38(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))))
44
45(define (copy-bit index to bool)
46  (if bool
47      (bitwise-ior to (arithmetic-shift 1 index))
48      (bitwise-and to (bitwise-not (arithmetic-shift 1 index)))))
49
50(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)))))
59
60(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)))
64
65(define (bits . bools)
66  (list->bits bools))
67
68(define (bitwise-if mask n0 n1)
69  (bitwise-ior (bitwise-and mask n0)
70          (bitwise-and (bitwise-not mask) n1)))