Bitfields

Anonymous anonymous at anonymous.anonymous
Mon Nov 9 19:57:49 UTC 2026


I'm considering betterC for porting a project written in C. Let's 
say I have a struct like this:

```D
struct Node {
   ubyte  Type: 5;
   bool   Is_Frob: 1;
   byte   Frob_Direction: 2;

   int  Regular_Field;
   /* more regular fields */
}
```

Syntactically this works fine, and all the bit fields fit into 
one byte. Now `Type` is actually enum, I can declare it as such 
and it should help ensure exhaustiveness of `switch` statements 
(very important for this project). In addition to that `Type` is 
also a struct of bit fields: there are several axes used to 
classify nodes, so there's a bit field for each axis. So what I 
really want is something like this:

```D
union Node_Type {
   struct {
     int  Axis_1: 2;
     int  Axis_2: 1;
     int  Axis_3: 2;
   }
   int Id: 5;
}

enum Node_Type_Id {
   Type_1_Id = Node_Type( Axis_1: 0, Axis_2: 1, Axis_3: -2 ).Id,
   ...
}

struct Node {
   union {
     Node_Type     Type;
     Node_Type_Id  Type_Id;
   }
   bool   Is_Frob: 1;
   byte   Frob_Direction: 2;
   ...
}

```
Is there a way to specify that the union of `Type` and `Type_Id` 
takes only 5 bits?


More information about the Digitalmars-d-learn mailing list