Bitfields in D

Dave P. dave287091 at gmail.com
Tue Oct 18 03:04:52 UTC 2022


[Adding bitfields to 
D](https://dlang.org/changelog/2.101.0.html#dmd.bitfields) for C 
interop is nice as it will automatically match the platform’s ABI 
for bitfields, but I don’t understand why we would want the 
implementation defined nightmare for regular D bitfields. One of 
the most annoying things about C bitfields is that if you use 
them,  you can’t just write your structs to disk or across the 
network as your format is immediately non-portable across 
different systems. That sucks as that’s exactly when you would 
want to save space with bitfields. Native D bitfields should 
avoid this problem.

However, you should be able to express that your struct including 
bitfields matches the layout of a C struct. I therefore propose 
that we tweak the syntax to require an extern(C) around bitfields 
matching C.

```D
struct A {
     extern(C) {
         int x:3, y:2;
     }
}
```
Or
```D
extern(C)
struct B {
     int x: 3, y:2;
}
```

And then have bitfields that aren’t extern(C) be illegal until 
the semantics are worked out. For example, [Adam’s 
ideas](http://dpldocs.info/this-week-in-d/Blog.Posted_2022_09_12.html#d-bitfields-could-be-good) could be good.


More information about the Digitalmars-d mailing list