Combine and unite the sequence of bytes in union
I am trying to combine and unite the sequence of bytes from an int and a short
when debugging and reading the memory it's aligned like this [FF FF FF FF 00 00 00 00]
shouldn't it looked like this [FF FF FF FF FF FF 00 00]
since i am using union?
union uniteByte{
unsigned int blockOne;
unsigned short blockTwo;
};
union uniteByte testing;
testing.blockOne =0xffffffff; //4294967295
testing.blockTwo = 0xffff; //65535
printf("%zu\n",sizeof(testing)); // size is 4 why? shouldn't it be 6?
printf("%u\n",testing.blockOne); // 4294967295
printf("%u\n",testing.blockTwo); // 65535
printf("%p",&testing); //0x7ffeefbff4e0 [FF FF FF FF 00 00 00 00]
printf("%p",&testing.blockOne); //0x7ffeefbff4e0 <-- the address is the same as in blockTwo
printf("%p",&testing.blockTwo); //0x7ffeefbff4e0 <-- the address is the same as in blockOne
The purpose of a union
is to use overlapping memory for each member, so the size is the size of the largest member, plus padding if necessary.
If you want the members to be independent, you have to use a struct
. To get rid of the padding between members and at the end, use __attribute__((packed))
.
Note that this will often have performance implications. CPU operations for moving numbers between memory and registers generally have alignment requirements, which is why structures normally have padding. When you pack the structure, the data has to be moved byte-by-byte instead of using single instructions for the full size of the number. So it should only be done when memory efficiency is at a premium and you need this time-space tradeoff.