Search code examples
cstructintendiannessuint32-t

How to store a struct member as big endian


I have a struct similar to:

typedef struct _pair_t{
    uint16_t    keylen;     // 2
    uint32_t    vallen;     // 4
} __attribute__((__packed__)) pair_t;

I will be using mmap to read from a file, so I want to store the numbers as big endian.

Do I need to do htobe16 / betoh16 or there is some __attribute__ that can do this for me?


Solution

  • You need to use htobe16 or htons or similar. There's no way in most compilers to declare a variable as having a different endianness.

    I'm aware of a (paid, commercial) compiler which had a switch to turn the entire program into the "opposite" endianness, but that's not quite what you want, and I'm sure you don't want to pay for it.