1

I have read from here that,

On a hypothetical "stupid-endian" C implementation where the bytes are neither big-endian (ordered 4321) nor little-endian (ordered 1234), but ordered for example 3214, you would still have htonl(ntohl(x)), but htonl and ntohl would not do the same thing, they'd be 8-bit rotations in opposite directions. I hope that no such architecture exists, but it could implement the sockets API thanks to the fact that htonl and ntohl are separate functions.

But I can't comprehend and figure out meaning of but htonl and ntohl would not do the samething, they'd be 8-bit rotations in opposite directions. What will be happen if they are rotated in opposite ways. How will the funcitons behave logically?

Can you depict and explain its logic?

P.S. It means in this case that implementations of htonl and ntohl functions are different and htonl(x) != ntohl(x)

concurrencyboy
  • 351
  • 1
  • 11
  • I’d like to highlight that your real question has nothing to do with htonl nor ntohl. You don’t understand the meaning of “rotating an int by byte(s) in either direction”. Once you dig that, the specific question you had will answer itself :) – Kuba hasn't forgotten Monica Aug 06 '18 at 00:44

1 Answers1

1

Suppose you had an architecture that stored the value 0x01020304 internally as 0x04010203. An implementation of ntohl would need to rotate the bytes right by 1.

For example:

uint32_t ntohl(uint32_t n)
{
    unsigned char x = n & 0xff;
    uint32_t result = n >> 8;
    result |= x << 24;
}

This would convert the value 0x01020304 to 0x04010203. Calling ntohl on the result 0x04010203 would not give back 0x01020304 but would instead give you 0x03040102.

To reverse the process you need to rotate left by 1 byte. An implementation of htonl might look like this:

uint32_t htonl(uint32_t n)
{
    unsigned char x = (n & 0xff000000) >> 24;
    uint32_t result = n << 8;
    result |= x;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thank you sir but, don't you write wrong the function name? I mean you need change htonl to ntohl an vice versa. Because network byte order always big-endian? – concurrencyboy Aug 06 '18 at 10:36