[plt-scheme] Integer-length

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Wed Mar 22 12:11:20 EST 2006

Is there a faster way of doing this?

   ; integer-length : non-negative-integer -> natural-number
   ;   return the number of bits needed to represent n
   (define (integer-length n)
     (unless (and (integer? n) (not (negative? n)))
       (error "a non-negative integer was expected, got: " n))
     (if (<= n 1)
         1
         (+ 1 (integer-length (arithmetic-shift n -1)))))


   > (map integer-length
          (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))
   (1 2 2 3 3 3 3 4 4 4 4 4 4 4 4 5)



See also:

<http://srfi.schemers.org/srfi-77/mail-archive/msg00017.html>

-- 
Jens Axel Søgaard





Posted on the users mailing list.