Number of Bits Needed to Represent a Zero-Offset Integer
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jan 19 10:37:12 PST 2015
On 1/19/15 12:35 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
> On Monday, January 19, 2015 08:30:47 Steven Schveighoffer via Digitalmars-d-learn wrote:
>> http://dlang.org/phobos/core_bitop.html#.bsr
>>
>> It's actually an intrinsic, reduces to an instruction. Mind the
>> requirements for 0.
>
> Sadly, I don't think that it have occurred to me from just reading the docs
> that that function would tell you how many bits it took to hold the value -
> though I don't know what else you'd use it for. In any case, thanks for the
> tip.
>
> - Jonathan M Davis
>
It tells you the most significant bit that is set. That is what you are
looking for, no?
Code:
import core.bitop;
import std.stdio;
void main()
{
foreach(x; 1..100)
writefln("x=%s, bsr(x)=%s", x, bsr(x)+1);
}
From the examples:
> value-set => bits
> =================
> 0,1 => 1 (*)
> 0,1,2 => 2
> 0,1,2,3 => 2 (*)
> 0,1,2,3,4 => 3
> 0,1,2,3,4,5 => 3
> 0,1,2,3,4,5,6 => 3
> 0,1,2,3,4,5,6,7 => 3 (*)
> 0,1,2,3,4,5,6,7,8 => 4
Output from test program:
x=1, bsr(x)=1
x=2, bsr(x)=2
x=3, bsr(x)=2
x=4, bsr(x)=3
x=5, bsr(x)=3
x=6, bsr(x)=3
x=7, bsr(x)=3
x=8, bsr(x)=4
...
Looks the same to me.
If you want the extra info of whether it's the full set (i.e. the *
elements above), then you can do simple x & (x+1) == 0.
-Steve
More information about the Digitalmars-d-learn
mailing list