Bit concatenation and masking and bit shifting

What are the disadvantages of using unions

when storing some information such as a series of bytes and being able to access them all at once or one by one.

Example: a color can be represented in RGBA. So the color type can be defined as

typedef unsigned int RGBAColor;

      

We can then use "offset and mask" bits to "get or set" the red, green, blue, alpha values โ€‹โ€‹of the RGBAColor object (just like we do in Direct3D functions with macros like D3DCOLOR_ARGB()

).

But what if I used union,

union RGBAColor
{
unsigned int Color;
struct RGBAColorComponents
{
    unsigned char Red;
    unsigned char Green;
    unsigned char Blue;
    unsigned char Alpha;
} Component;
};

      

Then I don't have to always do swap ( <<

) or masking ( &

) to read or write color components. But are there any problems with this? (I suspect this has some problems because I have not seen anyone using this method.)

Can Endianness be a broil? If we always use Component

to access the color components and use Color

to access the whole item (for copying, assigning, etc. in general), the continent shouldn't be a problem, right?

- EDIT - I found an old post that is the same problem. So I think this question is a kind of repost: P sorry. here is the link: Is it good practice to use unions in C ++?

As per the answers, it seems like using unions for the given example in C ++ is OK. Since there is no data type change, its two ways to access the same data. Please correct me if I am wrong. Thank you. :)

+3


source to share


2 answers


This use of unions is illegal in C ++, where a union contains overlapping but mutually exclusive objects. You are not allowed to write one member of the union and then read another member.

This is legal in C, where it is the recommended way of pinging words.



This refers to the problem of (strong) anti-aliasing, which is a difficulty that the compiler faces when trying to determine whether two objects of different types are different. Locales disagree as experts are still figuring out what guarantees can be safely provided without sacrificing performance. Personally, I avoid all of this. What will it be used for int

? A safe way to translate is to copy the bytes as in memcpy

.

There is also a content issue, but whether that depends on what you want to do with int

.

+1


source


I believe that using a union solves any content issues, as it is most likely that RGBA order is determined in network order. Also, the fact that each component will be uint8_t or such may help some compilers use signed / zero extended loads, storing low 8 bits directly into a non-stationary byte pointer, and even being able to parallelize some byte operations (e.g. 4x8 bits).



0


source







All Articles