C - 如何将数据类型“int”从主机转换为网络

时间:2021-09-15 16:32:02

We have htons and htonl to convert short/long types from host to network. What about the type of int?

我们有htons和htonl来将短/长类型从主机转换为网络。 int的类型怎么样?

Thanks!

谢谢!

1 个解决方案

#1


2  

It depends on the size of int. If it's 32-bit, use htonl and ntohl. If it's 16-bit, use htons and ntohs.

这取决于int的大小。如果它是32位,请使用htonl和ntohl。如果它是16位,请使用htons和ntohs。

If it's 64-bit, there's no standard function for that, so you'd have to roll your own. Here's an example of how you can do this in a portable way (i.e. doesn't depend on endianness):

如果是64位,则没有标准功能,所以你必须自己动手。以下是如何以可移植的方式执行此操作的示例(即,不依赖于字节顺序):

uint64_t htonll(uint64_t x)
{
    uint64_t result;
    unsigned char *c;

    c = (unsigned char *)&result;
    c[0] = x >> 56;
    c[1] = (x >> 48) & 0xFF;
    c[2] = (x >> 40) & 0xFF;
    c[3] = (x >> 32) & 0xFF;
    c[4] = (x >> 24) & 0xFF;
    c[5] = (x >> 16) & 0xFF;
    c[6] = (x >> 8) & 0xFF;
    c[7] = x & 0xFF;
    return result;
}

uint64_t ntohll(uint64_t x)
{
    uint64_t result;
    unsigned char *c;

    c = (unsigned char *)&x;
    result = (uint64_t)c[7];
    result |= (uint64_t)c[6] << 8;
    result |= (uint64_t)c[5] << 16;
    result |= (uint64_t)c[4] << 24;
    result |= (uint64_t)c[3] << 32;
    result |= (uint64_t)c[2] << 40;
    result |= (uint64_t)c[1] << 48;
    result |= (uint64_t)c[0] << 56;
    return result;
}

#1


2  

It depends on the size of int. If it's 32-bit, use htonl and ntohl. If it's 16-bit, use htons and ntohs.

这取决于int的大小。如果它是32位,请使用htonl和ntohl。如果它是16位,请使用htons和ntohs。

If it's 64-bit, there's no standard function for that, so you'd have to roll your own. Here's an example of how you can do this in a portable way (i.e. doesn't depend on endianness):

如果是64位,则没有标准功能,所以你必须自己动手。以下是如何以可移植的方式执行此操作的示例(即,不依赖于字节顺序):

uint64_t htonll(uint64_t x)
{
    uint64_t result;
    unsigned char *c;

    c = (unsigned char *)&result;
    c[0] = x >> 56;
    c[1] = (x >> 48) & 0xFF;
    c[2] = (x >> 40) & 0xFF;
    c[3] = (x >> 32) & 0xFF;
    c[4] = (x >> 24) & 0xFF;
    c[5] = (x >> 16) & 0xFF;
    c[6] = (x >> 8) & 0xFF;
    c[7] = x & 0xFF;
    return result;
}

uint64_t ntohll(uint64_t x)
{
    uint64_t result;
    unsigned char *c;

    c = (unsigned char *)&x;
    result = (uint64_t)c[7];
    result |= (uint64_t)c[6] << 8;
    result |= (uint64_t)c[5] << 16;
    result |= (uint64_t)c[4] << 24;
    result |= (uint64_t)c[3] << 32;
    result |= (uint64_t)c[2] << 40;
    result |= (uint64_t)c[1] << 48;
    result |= (uint64_t)c[0] << 56;
    return result;
}