Reputation: 507
I recently came accross this code and I can't get my head around it. Could someone, please, explain me what is happening there?
union Color32
{
struct ARGB
{
uint8_t b;
uint8_t g;
uint8_t r;
uint8_t a;
} parts;
uint32_t argb;
Color32() : argb(0) {}
Color32(uint32_t c_argb) : argb(c_argb) {}
Color32(uint8_t a, uint8_t r, uint8_t g, uint8_t b)
{
parts.a=a;
parts.r=r;
parts.g=g;
parts.b=b;
}
};
Upvotes: 1
Views: 91
Reputation: 8589
The members of a union
share storage. This is in contrast to a struct
where each member is allocated distinct storage.
The effect of this code is that the members b
,g
,r
& a
of the ARGB
struct share storage with the other member argb
of the Color32
union
.
So the constructor that sets the value of argb
implicitly sets the values of b
,g
,r
& a
as the ordered parts of the bit pattern of argb
.
Conversely the b
,g
,r
& a
constructor builds up the value of argb
.
The diagram under 'ARGB' here is a really good picture of how those parts are 'packed' into a 32 bit block.
http://en.wikipedia.org/wiki/RGBA_color_space
I probably don't need to explain that b
stands for blue, g
green , r
for red and a
for alpha (AKA Transparency)!
You may encounter difficulties if there is a requirement for big-endian /little-endian portability.
Upvotes: 4
Reputation: 453
ARGB is a structure of 4 uints which represents green, blue, red and for a I don't know. The structure is created with the name parts so when you have to use it you must act like: parts.r = 20 or parts.g = 50.
Then it create an object color which can contain the 4 parameters of the argb (4*8 = 32).
And it initialized the object color 32 with the 4 parameters that you give him : a,b,c,d
Color32(uint8_t a, uint8_t r, uint8_t g, uint8_t b)
{
parts.a=a;
parts.r=r;
parts.g=g;
parts.b=b;
}
To resume, you have an object named Color of 32 bits which contains 4 objects of 8 bits from the structure parts.
Upvotes: 0