0

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?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Nick
  • 9,962
  • 4
  • 42
  • 80
  • 1
    Sidenote: You shouldn't define types that end with `_t` to avoid possible conflicts with built-in compiler types. – user694733 Jan 07 '15 at 07:34
  • 1
    @Sidenote - I use hm_pair_t (I prepend hm_ everywhere I also use _t for all typedefs). Should I fix this in my code? Is there good howto for this kind of naming? – Nick Jan 07 '15 at 07:38
  • 1
    Names that start with `_` are also reserved. – Jasen Jan 07 '15 at 07:52
  • [This answer](http://stackoverflow.com/a/231807/694733) has some discussion about it. I have used `CamelCaseWithSuffix_T` convention in C, but don't know if it's best. – user694733 Jan 07 '15 at 07:54

1 Answers1

5

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436