https://commandcenter.blogspot.com/2012/04/byte-order-fallac...
And will a compiler make use of native byte swapping instructions with the code proposed by the author?
https://commandcenter.blogspot.com/2012/04/byte-order-fallac...
And will a compiler make use of native byte swapping instructions with the code proposed by the author?
I think this is also the main point of the post you linked: the "bad" example has a numeric value and then performs byte swapping on it, the "good" examples only ever construct "correctly ordered" numeric values.
If you can possibly get to a place where you have a uint16 but the value is "in the wrong byte order", you've done something wrong already.
Admitting the possibility of values with the wrong byte order into your system casts every single value into doubt. Of course it's possible to resolve that doubt on a case-by-case basis by carefully identifying the right places to insert ntohs()/htons() calls, but to me that sounds like creating extra chores for yourself while working against the language.
A proper abstraction is the one where you specify both the size and the endianness at the point where you extract the value - i.e. where you just call a function like read_int16_be(byte_stream).
That isn't guaranteed. sizeof(short) and sizeof(int) are both allowed to be 1 on a system with chars at least 16 or 32 bits wide, respectively.
Which just goes to show that these are not the types you want to be using for any kind of portable binary I/O.
Put another way, Pike is saying that libc should have implemented be16toh() like:
# define be16toh(x) ( (((char*)x)[1]<<0) | (((char*)x)[0]<<8) )
instead of how GNU libc implemented it: # if __BYTE_ORDER == __LITTLE_ENDIAN
# define be16toh(x) __bswap_16 (x)
# else
# define be16toh(x) __uint16_identity (x)
# endif
But that complaint doesn't affect programs that call be16toh().Whether there's a endianness conditional anywhere there or not is a bit of pedantry, I think.