

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Union
incomplete
2: Memory Layout
incomplete
3: Union Size
incomplete
4: Helper Fields
incomplete
This lesson's interactive features are locked, please to keep using them
One interesting (albeit not commonly used) trick is to use unions to create "helpers" for accessing different parts of a piece of memory. Consider the following:
typedef union Color {
struct {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
} components;
uint32_t rgba;
} color_t;
It results in a memory layout like this:
Only 4 bytes are used. And, unlike in 99% of scenarios, it makes sense to both set and get values from this union through both the components and rgba fields! Both fields in the union are exactly 32 bits in size, which means that we can "safely" (?) access the entire set of colors through the .rgba field, or get a single color component through the .components field.
The convenience of additional fields, with the efficiency of a single memory location!
and the fragility of C...
Sneklang has support for networking!
Complete the PacketHeader union. It should have two potential fields:
Use uint8_t, uint16_t, and uint32_t for the types of the fields, based on the number of bytes needed. Remember, 8 bits = 1 byte.