Number of Bits Needed to Represent a Zero-Offset Integer
bearophile via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 13 04:28:23 PST 2015
Dominikus Dittes Scherkl:
> I would recommend to use something like this:
>
> /// returns the number of the highest set bit +1 in the given
> value or 0 if no bit is set
> size_t bitlen(T)(const(T) a) pure @safe @nogc nothrow
> if(isUnsigned!T)
> {
> static if(T.sizeof <= size_t.sizeof) // doesn't work for
> ulong on 32bit sys
> {
> return x ? core.bitop.bsr(x)+1 : 0;
> }
> else static if(T.sizeof == 8) // ulong if size_t == uint
> {
> return x ? x>>32 ? core.bitop.bsr(x)+33 :
> core.bitop.bsr(x)+1 : 0;
> }
> }
Is this good to be added to Phobos? Perhaps with a more
descriptive name?
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list