constexpr and endianness

New answer (C++20) c++20 has introduced a new standard library header <bit>. Among other things it provides a clean, portable way to check the endianness. Since my old method relies on some questionable techniques, I suggest anyone who uses it to switch to the check provided by the standard library. Here’s an adapter which allows … Read more

Detecting Endianness

As stated earlier, the only “real” way to detect Big Endian is to use runtime tests. However, sometimes, a macro might be preferred. Unfortunately, I’ve not found a single “test” to detect this situation, rather a collection of them. For example, GCC recommends : __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ . However, this only works with latest versions, … Read more

Is there a way to do a C++ style compile-time assertion to determine machine’s endianness?

If you’re using autoconf, you can use the AC_C_BIGENDIAN macro, which is fairly guaranteed to work (setting the WORDS_BIGENDIAN define by default) alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branch) int is_big_endian() { union { … Read more

Is there a way to enforce specific endianness for a C or C++ struct?

A bit late to the party but with current GCC (tested on 6.2.1 where it works and 4.9.2 where it’s not implemented) there is finally a way to declare that a struct should be kept in X-endian byte order. The following test program: #include <stdio.h> #include <stdint.h> struct __attribute__((packed, scalar_storage_order(“big-endian”))) mystruct { uint16_t a; uint32_t … Read more

How to write endian agnostic C/C++ code?

The only time you have to care about endianness is when you’re transferring endian-sensitive binary data (that is, not text) between systems that might not have the same endianness. The normal solution is to use “network byte order” (AKA big-endian) to transfer data, and then swizzle the bytes if necessary on the other end. To … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)