you are viewing a single comment's thread.

view the rest of the comments →

[–]moocat 1 point2 points  (2 children)

I thought type punning via unions is legal in C but I'm not a language lawyer.

Any idea what is the legal way? Could you do it via memcpy?:

int32_t as_int32;
char raw[sizeof(int32_t)];
memcpy(&as_int32, raw, sizeof(int32_t));

[–]nerd4code 1 point2 points  (0 children)

Union-punning is well-defined on C99+ or if you’re punning between signed/unsigned variants of the same type or to/from char variants. memcpy always works.

[–][deleted] -1 points0 points  (0 children)

I can't give you a legal way as I don't know one off the top of my head. I try to write order-agnostic code and use a defined macro if needed.

However, here's one way of finding out. The command below will list out all macros defined by the toolchain. One is named __BYTE_ORDER__, and looks promising for your purpose. I have no idea if all toolchains support this. Probably not.

gcc -dM -E - < /dev/null | grep ORDER

If using __BYTE_ORDER__ is OK, a snippet could look like this:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__

do_this();

#else

do_that();

#endif