Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of bytes in struct

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?

like image 987
Arjun Sreedharan Avatar asked Nov 02 '15 06:11

Arjun Sreedharan


1 Answers

Does it depend on the endianness?

Yes it does depends on the endianness of the machine. So your logic will change depending on the endianness of the machine.

There is no portable way* to do it because of structure padding. Although different compilers do provide custom ways to disable struct padding. Check Force C++ struct to not be byte aligned.

  • You can add a static_assert (requires C11 support) just to be sure that your code doesn't compiles unless your struct is tightly packed. You won't have portable code but you still can be sure that if your code compiles, it will behave correctly.

    static_assert(sizeof(container) == sizeof(int) + sizeof(short) + sizeof(long));
    
like image 145
bashrc Avatar answered Oct 04 '22 11:10

bashrc