Should all structures that should be read from binary be marked as packed?

I know that some structures may or may not add padding between elements.

My current project is reading input from / dev / input files. The binary layout of these files is defined in <linux/input.h>:

struct input_event {
    struct timeval time;
    __u16 type;
    __u16 code;
    __s32 value;
};

Interestingly, this structure is not marked with a packed attribute . This means that the / dev / input files (which are packaged bit by bit) do not guarantee compliance with the same package as the structure. So the logic

struct input_event event;
read(fd, &event, sizeof(event));

Not defined to work in all arches.

Do I have a mistake in my logic? Or is it safe to assume that something is not going to be packed?

+6
2

. input_event , .

struct timeval time;  /* 8 bytes */
__u16 type;           /* 2 bytes */
__u16 code;           /* 2 bytes */
__s32 value;          /* 4 bytes */

, 32Bit . , ( ) , , .

, -, . , , (. #pragma pack effect)

, (4- 32- 8- 64- ). , .

(, )

. , .

( ), NTP . , , , , .

+2

, C . , . 8 . int32_t .. , -.

. , .

16- . . github ( ) https://github.com/MalcolmMcLean/ieee754

/**
  Get a 16-bit big-endian signed integer from a stream.
  Does not break, regardless of host integer representation.
  @param[in] fp - pointer to a stream opened for reading in binary mode
  @ returns the 16 bit value as an integer
*/
int fget16be(FILE *fp)
{
    int c1, c2;

    c2 = fgetc(fp);
    c1 = fgetc(fp);

    return ((c2 ^ 128) - 128) * 256 + c1;
}
+1

Source: https://habr.com/ru/post/1014655/


All Articles