chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] Numbers weirdness


From: Peter Bex
Subject: Re: [Chicken-users] Numbers weirdness
Date: Fri, 1 Apr 2016 19:35:24 +0200
User-agent: Mutt/1.5.23 (2014-03-12)

On Fri, Apr 01, 2016 at 06:23:28PM +0100, Andy Bennett wrote:
> Thanks Peter!
> 
> I'm mostly using log2 to work out if numbers are a power of two and find
> the highest bit that they have set.
> 
> Is there a more robust way to do that in CHICKEN when using the numbers
> egg and bignums?

It's probably better to do something like this:

(= (arithmetic-shift 1 (sub1 (integer-length x))) x)

If you find it clearer, you can also use

(= (expt 2 (sub1 (integer-length x))) x)

Note that the former accepts zero as a power of two, while the latter
doesn't.

And if you want to have some fun with bits:

(zero? (bitwise-xor (arithmetic-shift 1 (sub1 (integer-length x))) x))

Maybe we should consider including "first-bit-set" or "logcount" from
SRFI-60, what do you think?  These would allow us to avoid constructing
potential bignums just to check the lowest bit.  I initially decided
against including SRFI-60 because it's such a huge grab-bag of
procedures without much of a design behind it, and the worst part is
that most of them have two names instead of one :(

Cheers,
Peter

Attachment: signature.asc
Description: Digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]