bitwise.scm 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. ; Part of Scheme 48 1.9. See file COPYING for notices and license.
  2. ; Authors: Richard Kelsey, Jonathan Rees
  3. ; Bitwise operators written in vanilla Scheme.
  4. ; Written for clarity and simplicity, not for speed.
  5. ; No need to use these in Scheme 48 since Scheme 48's virtual machine
  6. ; provides fast machine-level implementations.
  7. (define (bitwise-not i)
  8. (- -1 i))
  9. (define (bitwise-and x y)
  10. (cond ((= x 0) 0)
  11. ((= x -1) y)
  12. (else
  13. (+ (* (bitwise-and (arithmetic-shift x -1)
  14. (arithmetic-shift y -1))
  15. 2)
  16. (* (modulo x 2) (modulo y 2))))))
  17. (define (bitwise-ior x y)
  18. (bitwise-not (bitwise-and (bitwise-not x)
  19. (bitwise-not y))))
  20. (define (bitwise-xor x y)
  21. (bitwise-and (bitwise-not (bitwise-and x y))
  22. (bitwise-ior x y)))
  23. (define (bitwise-eqv x y)
  24. (bitwise-not (bitwise-xor x y)))
  25. (define (arithmetic-shift n m)
  26. (floor (* n (expt 2 m))))
  27. (define (count-bits x) ; Count 1's in the positive 2's comp rep
  28. (let ((x (if (< x 0) (bitwise-not x) x)))
  29. (do ((x x (arithmetic-shift x 1))
  30. (result 0 (+ result (modulo x 2))))
  31. ((= x 0) result))))
  32. ;(define (integer-length integer) ...) ;?