htonl problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • absolute0
    New Member
    • Feb 2008
    • 8

    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....
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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.

    Comment

    • absolute0
      New Member
      • Feb 2008
      • 8

      #3
      I forgot to mention, this was in Linux, btw. The four bits shift to the right is part of the program's requirement.

      Comment

      Working...