Endianness conversions broken?

While writing my own IP stack, I have come across a small "issue" with htons, htonl, etc.

It seems that the routines don't do anything.

The Arduino is meant to be little-endian, yes? And network order is big-endian. Yet, the following code:

        uint32_t t = 94737692;
        Serial.print("Host: ");
        Serial.print(t);
        Serial.print(" Network: ");
        Serial.println(htonl(t));

gives:

Host: 94737692 Network: 94737692

Whereas surely it should give:

Host: 94737692 Network: 479569157

Am I correct in my assumption that it's just plain broken in the library?

Have you tried the opposite function to see what happens?

I'm not too sure if this is implemented in Arduino. :\

I think you'll find that the Arduino is big-endian and therefore no conversion is necessary.

That's not what I read on other posts in this self same forum...

Take for example: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1228184935

John_Ryan is correct: the processor is little endian.

And:

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210883097

GCC (used by Arduino) seems to be little-endian by default.

And so on...

So, although the processor, being 8 bit, doesn't actually have an endian-ness per se, the compiler does, and that is little-endian.

I have implemented my own _htons() etc functions, and everything is working fine, but it would kind of be nice if the library routines actually did anything.

It works for me using Arduino-1. Are you sure you’re importing the correct htonl() ? (should be in Ethernet/util.h I had to add an explicit “#include <util.h>” to the “ChatServer” example that I added your code to to try this out…)


htonl et al should be a part of the standard C libraries. If the right header isn't included it should whinge about "implicit declaration" stuff - which it doesn't - so no header is required.

On a Linux system it relies on the arpa/inet.h header for definitions. Obviously, that doesn't exist on Arduino. Relying on a third party library for the headers seems kind of lame and backwards. Either something in the core library should be supported in the core or it shouldn't exist in the core. It shouldn't be in the core yet rely on an external library to provide definitions for it.