Number of Bits Needed to Represent a Zero-Offset Integer

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jan 19 04:31:14 PST 2015


On Mon, 19 Jan 2015 12:04:38 +0000
via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:

> As a follow-up to
> 
> http://forum.dlang.org/thread/fdfwrdtjcawprvvkoqas@forum.dlang.org#post-qxudiyoygnvvbovhjfgt:40forum.dlang.org
> 
> I'm looking for a function that figures out the number of bits 
> that are needed to represent a zero-based integer:
> 
> 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
> ...
> 
> (*) means full bit usage

  template minbits (uint n) {
    import std.math : log2;
    enum minbits = (n ? cast(int)(log2(n))+1 : 1);
  }

  template btest (uint n) {
    static if (n <= 64) {
      import std.conv;
      pragma(msg, to!string(n)~"="~to!string(minbits!n));
      enum btest = btest!(n+1);
    } else {
      enum btest = 666;
    }
  }

  enum t = btest!0;
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150119/148c9982/attachment.sig>


More information about the Digitalmars-d-learn mailing list