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

Re: [FWP] Counting bits from the other end



On Mon, May 01, 2000 at 04:17:07PM -0400, Bernie Cosell wrote:
> 
> a & (a-1) turns off the lowest-order bit in a (binary) number.  Can you 
> find some reasonable way to turn off the *highest* order bit in the 
> number?  Best I could find was to do the a&(a-1) in a loop and just 
> remember the last-nonzero-value... but it'd sure be neat if there was a 
> trick to find that bit directly without the loop...

How about this?

sub high_off {
    my $n = shift;

    $n -= 2 ** int(log($n) / log(2));
}

Ronald

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe