質問

I have found the following function from MSDN which converts an unsigned long from network byte to unsigned long in host byte order i.e. in little-endian defined as:

u_long WSAAPI ntohl(
       _In_  u_long netlong
);

The MSDN document says that it can convert a 32 bits number. But since in C++ as I have read that long and int are not the same i.e. long is not guaranteed to be 32 bits or the same size of an integer INT_MAX.

So, I wonder if there is a a similar function which takes a 32 bits values such as unsigned int instead of unsigned long?

役に立ちましたか?

解決

The documentation specifically says that ntohl's netlong parameter is a 32-bit value:

netlong [in]

A 32-bit number in TCP/IP network byte order.


I have read that long and int are not the same i.e. long is not guaranteed to be 32 bits or the same size of an integer INT_MAX.

You're right -- in Standard C++ a long is not guaranteed to be any particular size, except that it must be at least 32 bits.

However since we're talking about the endian conversion functions, we're talking about platform-specifics here. We need to drill down now in to what a long is under Windows. And under Windows, a long is 32-bits:

LONG

A 32-bit signed integer. The range is –2147483648 through 2147483647 decimal. This type is declared in WinNT.h as follows:

typedef long LONG;

他のヒント

ntohl() and htonl() always operate on 32-bit values on all platforms. That is part of the BSD standard. On platforms where (u_)long is larger than 32-bits, a different 32-bit data type will be used instead. For instance, some platforms, including Linux and FreeBSD, use uint32_t to avoid any issues with the size of (u_)long.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top