Number of Bits Needed to Represent a Zero-Offset Integer
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 13 07:12:19 PST 2015
On Fri, Feb 13, 2015 at 12:28:23PM +0000, bearophile via Digitalmars-d-learn wrote:
> 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?
[...]
Isn't it essentially floor(log_2(a)), mathematically speaking? Maybe
that could be the basis of a better name?
T
--
Lawyer: (n.) An innocence-vending machine, the effectiveness of which depends on how much money is inserted.
More information about the Digitalmars-d-learn
mailing list