2

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?

cpx
  • 17,009
  • 20
  • 87
  • 142

2 Answers2

1

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;
Community
  • 1
  • 1
John Dibling
  • 99,718
  • 31
  • 186
  • 324
  • Does this mean that if I pass `u_int` to the function it will be fine? Because the function accepts `u_long` as input which may or may not be 32 bits. – cpx Jan 15 '14 at 17:19
  • @cpx: Under Windows, an `int` is also a 32-bit integer. See the documentation I linked. – John Dibling Jan 15 '14 at 17:22
0

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770