Union with bits ?
Ali Çehreli
acehreli at yahoo.com
Wed Jun 14 14:43:58 UTC 2023
On 6/13/23 17:59, Paul wrote:
> I would like to have labeled bits in a union with a ubyte. Something
> like this:
> ```d
> struct MyStruct {
> union {
> ubyte status;
> bit A, B, C…etc
> }
> }
> ```
> Is something like this possible?
>
> Thanks
D's string mixin syntax may not be the best, the implementation may be
slower than necessary, and the concept may be strange (not macros but
very similar) but I still find phobos's bifields to be brilliant.
https://dlang.org/phobos/std_bitmanip.html#bitfields
import std.bitmanip;
struct MyStruct {
union {
ubyte status;
mixin(bitfields!(
ubyte, "A", 1,
ubyte, "B", 1,
ubyte, "C", 1,
ubyte, "padding", 5,));
}
}
void main() {
auto m = MyStruct();
m.B = 1;
assert(m.status == 2);
}
Ali
More information about the Digitalmars-d-learn
mailing list