Packing enums

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 29 17:30:15 PDT 2015


On Monday, 29 June 2015 at 22:05:47 UTC, qznc wrote:
> I stumbled upon this interesting programming challenge [0], 
> which imho should be possible to implement in D. Maybe someone 
> here wants to try.
>
> Task: Given two enums with less than 256 states, pack them into 
> one byte and provide convenient accessor functions.
>
> Something like this:
>
> enum X { A, B, C };
> enum Y { foo, bar, baz };
> alias both = TwoEnums!(X,Y);
> static assert(both.sizeof == 1);
> both z;
> z.X = B;
> z.Y = bar;
>
> Of course, you can generalize to "n enums packed into a minimal 
> number of bytes".
>
>
> [0] https://news.ycombinator.com/item?id=9800231

Have you tried using bitfields?

  enum X : byte { A, B, C };
  enum Y : byte { foo, bar, baz };


mixin(bitfields!(
         X, "x",    3,
         Y,  "y",    3,
         uint, "",  2));





More information about the Digitalmars-d-learn mailing list