Search code examples
csocketsintunsigned-integer

Convert Integer to Unsigned Long


Trying to use the function htonl() for a program that sends an init message to a server, along with an integer value, say 5. However, htonl() needs the following uint32_t integer hostlong

How can I convert 5 to an unsigned integer?


Solution

  • The htonl function is declared in <arpa/inet.h>. Assuming you have a proper #include for that header:

    #include <arpa/inet.h>`
    

    the declaration

    uint32_t htonl(uint32_t hostlong);
    

    will be visible, so the compiler knows the expected argument type and the result type.

    If you want to pass the value 5 to the htonl function, just pass it:

    uint32_t result = htonl(5);
    

    The constant 5 is of type int. The compiler will generate an implicit conversion from int to uint32_t. (It's likely the conversion won't actually have to do anything.)

    If the value 5 is stored in an int object, it's the same thing:

    int n = 5;
    uint32_t result = htonl(n);
    

    No explicit conversion (cast) is necessary.

    (Incidentally, there's an important distinction between "int" and "integer". There are a number of integer types, including short, unsigned long, uint32_t, and so forth. int is the name of one of those types. An unsigned long value is an integer.)