468,512 Members | 1,402 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

htonl problem

Suppose I had the following code:

unsigned int a = 0xb07b6fde;
unsigned long b = htonl(a);
b = b >> 4;
printf("int: %d\n", b);
printf("hex: %x\n", b);

printf("\n");

unsigned int c = 0xb07b6fde;
unsigned long d = htonl(c) >> 4;
printf("int: %d\n", d);
printf("hex: %x\n", d);

The output would be:
int: 233240507
hex: de6f7bb

int: -35194949
hex: fde6f7bb

Why is the second result different? As far as I know, >> for signed numbers uses arithmetic shift while that for unsigned uses logical shift. htonl() supposedly returns uint32_t which is unsigned.

Also if <netinet/in.h> is included, the second result would be the same as the first....
Feb 18 '08 #1
2 7012
weaknessforcats
9,207 Expert Mod 8TB
htonl() converts between the byte order of a server to the TCP/IP network's byte order. In the case of a Windows server this is a conversion between little endian and big endian.

After htonl() call, the variable, in the case of Windows, is big endian but any functions will see it as little endian. Result: Garbage.

I have no idea what your shifting is about,. Especially 4 bits.
Feb 18 '08 #2
I forgot to mention, this was in Linux, btw. The four bits shift to the right is part of the program's requirement.
Feb 19 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Bruce Davis | last post: by
11 posts views Thread by Kostatus | last post: by
117 posts views Thread by Peter Olcott | last post: by
28 posts views Thread by Jon Davis | last post: by
6 posts views Thread by Ammar | last post: by
2 posts views Thread by Mike Collins | last post: by
2 posts views Thread by linuxer | last post: by
1 post views Thread by Tom Impelluso | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.