Reputation: 612
I am getting some data from a DNS server and I am trying to convert a certain part into an unsigned int (which represents the refresh interval, expiration etc). By conversion, I mean from big endian to little endian. The problem is that the ntohs places only 2 bytes of data instead of 4.
memcpy(&number, data, 4);
printf("%x ",number);
number = ntohs(number);
printf("%x ",number);
Output:
b6fc0b78 780b
About the types:
:t data
char*
:t number
unsigned int
The weird thing is that even by trying using bit shifts to reconstruct the number, the values are pretty different: like 0, for example.
How could I get 780bfcb6 from b6fc0b78 into an unsigned int?
Upvotes: 0
Views: 1532
Reputation: 140540
Notice that 780b
is the byte-swap of 0b78
, which is the low 16 bits of the number you passed in.
The s
in ntohs
is for short
. It operates on uint16_t
quantities. The argument and return type of ntohs
are unsigned int
only because it predates C89 prototypes; in K&R C it was impossible to express that a function took an argument shorter than int
. (The latest POSIX specification seems to have decided that this historical wart is no longer necessary. I can persuade GCC and clang to warn about this mistake, but only by using -Wconversion
, which is not turned on by -Wall
, -Wextra
, nor -pedantic
.)
The function you are looking for is ntohl
. It operates on uint32_t
quantities, which is what you want. (The l
is for long
, but it dates to a time when 64-bit long
was unheard of.)
Upvotes: 3