Union individual bits of bitfield

2 days ago 4
ARTICLE AD BOX

You can accomplish this in C by using a union of two structures (as well as your raw member). In one structure, put one of the two bit-fields you wish to overlay and all the other bit-fields. In the other structure, put the other bit-field you wish to overlay and anonymous fields to replicate the layout of the first structure.

struct OAMAttribute0 { union { u16 raw; struct { u16 ypos : 8; // 0-255 u16 rotation_scaling: 1; // 0=off, 1=on u16 double_size : 1; // when rotation/scaling used u16 mode : 2; // 0=normal, 1=semi-transparent, 2=obj window, 3=prohibited u16 mosaic : 1; // 0=off, 1=on u16 colors : 1; // 0=16/16, 1=256/1 u16 shape : 2; // 0=square, 1=horizontal, 2=vertical, 3=prohibited }; struct { u16 : 8; u16 : 1; u16 obj_disable : 1; // 0=normal, 1=not displayed u16 : 2; u16 : 1; u16 : 1; u16 : 2; }; }; };

The C++ standard does not provide for anonymous structures, but some compilers may support it.

This is not to say it is a good idea.

Eric Postpischil's user avatar

What you want isn't possible. A union or struct type has to be at least 1 bytes in length.

The closest thing you can do is use a #define to alias one field as the other.

dbush's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article