具有 htonl 和 ntohl 功能的 pdp endian

pdp endian with htonl and ntohl functions

我从 here 那里了解到,

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.

但我无法理解和弄清楚 的含义,但是 htonlntohl 不会做同样的事情,它们会在相反方向上进行 8 位旋转. 如果它们以相反的方式旋转会发生什么。函数的逻辑行为如何?

你能描述并解释它的逻辑吗?

P.S。这意味着在这种情况下 htonlntohl 函数的实现是不同的并且 htonl(x) != ntohl(x)

假设您的架构在内部将值 0x01020304 存储为 0x04010203ntohl 的实现需要将字节右移 1。

例如:

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

这会将值 0x01020304 转换为 0x04010203。在结果 0x04010203 上调用 ntohl 不会返回 0x01020304 而是返回 0x03040102.

要反转此过程,您需要将向左 循环 1 个字节。 htonl 的实现可能如下所示:

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