I am a little confused about how bytes are ordered in a struct
.
Let's say I have the following struct:
struct container {
int myint;
short myshort;
long mylong;
};
Now, I want to initialize a variable of type struct container
just like the following, except that I want to do it using an array.
struct container container1 = {.myint = 0x12345678,
.myshort = 0xABCD,
.mylong = 0x12345678};
Assume sizeof
int
and long
are 4
, and that of short
is 2
.
Assume there is no padding.
How would then the layout of the 10 bytes
of the struct
be?
Does it depend on the endianness?
Would be it be like:
0x12345678 ABCD 12345678
or like:
0x78563412 CDAB 78563412
What I want to do is: I have the following char array:
char buffer[10] = {0};
I want to manually fill this array with data and then memcpy
to the struct
.
Should I be doing[1]:
buffer[0] = 0x12345678 & 0xFF;
buffer[1] = 0x12345678 >> 8 & 0xFF;
buffer[2] = 0x12345678 >> 16 & 0xFF;
buffer[3] = 0x12345678 >> 24 & 0xFF;
...
buffer[9] = 0x12345678 >> 24 & 0xFF;
or should it be[2]:
buffer[0] = 0x12345678 >> 24 & 0xFF;
buffer[1] = 0x12345678 >> 16 & 0xFF;
buffer[2] = 0x12345678 >> 8 & 0xFF;
buffer[3] = 0x12345678 & 0xFF;
...
buffer[9] = 0x12345678 & 0xFF;
before I do my memcpy
like:
memcpy(&container1, buffer, sizeof(container1);
And, if I am writing to an array and copying to struct
, Is it portable across systems, especially with regards to endianness?
EDIT: Does [1] work on a little endian machine and [2] on a big endian?