concurrencyboy
concurrencyboy

Reputation: 371

pdp endian with htonl and ntohl functions

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)

Upvotes: 1

Views: 228

Answers (1)

dbush
dbush

Reputation: 225537

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;
}

Upvotes: 1

Related Questions