fixing off-by-one error in first-set-bit

This commit is contained in:
Alex Shinn 2017-05-19 23:04:06 +09:00
parent d3c2306220
commit e0fe160f46
2 changed files with 9 additions and 1 deletions

View file

@ -36,7 +36,7 @@
(define (first-set-bit i)
(if (zero? i)
-1
(integer-length (- i (bit-and i (- i 1))))))
(- (integer-length (- i (bit-and i (- i 1)))) 1)))
(define (mask len)
(- (arithmetic-shift 1 len) 1))

View file

@ -132,6 +132,14 @@
(test #b1010111 (bits #t #t #t #f #t #f #t))
(test #b1010111 (bits #t #t #t #f #t #f #t #f #f))
(test 0 (first-set-bit 1))
(test 1 (first-set-bit 2))
(test -1 (first-set-bit 0))
(test 3 (first-set-bit 40))
(test 2 (first-set-bit -28))
(test 99 (first-set-bit (expt 2 99)))
(test 99 (first-set-bit (expt -2 99)))
(test '(#t #f #t #f #t #t #t) (bitwise-fold cons '() #b1010111))
(test 5