SPUG: Cool power-of-2 trick

Ken Clarke kenslinux at shaw.ca
Fri Jan 21 03:37:41 PST 2005


----- Original Message ----- 
From: "Aaron W. West" <tallpeak at hotmail.com>
Sent: Thursday, January 20, 2005 2:42 PM
Subject: Re: SPUG: Cool power-of-2 trick


>I wonder if there's a quick way to find the smallest power of two equal to
> or greater than a given number.

Sure, by counting the number of characters in the binary representation of 
the given number less 1, then raising 2 to the power of the count:

$smallest_power_of_two = 2**(length(sprintf "%b", $given_number - 1));

$given_number must be  > 1 because subtracting 1 does not produce a zero 
character binary representation.  You know that the answer for all numbers 
below 2 (including negative numbers) is 1 anyway (2**0 = 1).  I also found 
that it breaks down for given numbers larger than 2**30 but your mileage may 
vary as they say...

There are 10 types of people in the world; those who know binary and those 
who don't.

>> Ken Clarke
>> Contract Web Programmer / E-commerce Technologist
>> www.PerlProgrammer.net





More information about the spug-list mailing list