Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 21 Aug 1999 23:59:48 +0930
From:      Leigh Hart <hart@dotat.com>
To:        FreeBSD Hackers mailing list <hackers@FreeBSD.ORG>
Subject:   Re: from number to power of two 
Message-ID:  <199908211429.XAA18455@at.dotat.com>
In-Reply-To: Your message of "Sat, 21 Aug 1999 12:54:32 %2B0200." <Pine.BSF.4.10.9908211250310.7595-100000@heidi.plazza.it> 

next in thread | previous in thread | raw e-mail | index | archive | help

G'day Nick,

Nick Hibma <n_hibma@skylink.it> wrote:
> 
> Does anyone know an inexpensive algorithm (O(1)) to go from
> an number to the next (lower or higher) power of two.
> 
> 1			-> 1
> 2,3			-> 2
> 4,5,6,7			-> 4
> 8,9,10,11,12,13,14,15	-> 8
> etc.
> 
> So %1101 should become either %10000 or %1000.

a bitwise shift left (to higher) or right (to lower) before or
after masking out all but the most significant bit in the number.

You just need to know how many bits to mask based on where the
most significant bit is ;]

I was tempted to throw something together but its late, and the
idea should be enough to go on ...

Cheers

Leigh
-- 
| "By the time they had diminished | Leigh Hart, <hart@dotat.com> |
|  from 50 to 8, the other dwarves | CCNA - http://www.cisco.com/ |
|  began to suspect 'Hungry' ..."  | GPO Box 487 Adelaide SA 5001 |
|   -- Gary Larson, "The Far Side" |  http://www.dotat.com/hart/  |


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199908211429.XAA18455>