next power of 2

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sat Oct 6 13:58:49 PDT 2012


On 10/6/12 4:57 PM, Dmitry Olshansky wrote:
> On 07-Oct-12 00:54, Dmitry Olshansky wrote:
>> On 07-Oct-12 00:48, ref2401 wrote:
>>> is there any Phobos function to calculate the next power of 2 of the
>>> specified number?
>>
>> No though it's reinvented in a couple of places I think.
>>
>> Anyway this should work for unsigned numbers:
>>
>> import core.bitop;
>> T nextPow2(T)(T x){
>> return x == 0 ? 1 : 1^^(bsr(x)+1);
>> }
>
> Yikes, 1<<(bsr(x)+1) or 2 ^^ (bsr(x)+1) ...
> still haven't got used to 2^^x notation compared to shifts.

That's right, apologies for my buggy suggestion and my suggestion of a 
buggy suggestion :o).

Andrei



More information about the Digitalmars-d-learn mailing list