what does ntohl(*(uint32_t*) …)do?

后端 未结 2 679
夕颜
夕颜 2021-01-24 11:17
ip=ntohl(*(uint32_t*)PQgetvalue(result, i, 0));

What is the meaning of this code segment?

My guess is that this code takes an input from Postgr

2条回答
  •  天命终不由人
    2021-01-24 12:17

    According to the docs:

    For most queries, the value returned by PQgetvalue is a null-terminated ASCII
    string representation of the attribute value. But if PQbinaryTuples() is TRUE,
    the value returned by PQgetvalue is the binary representation of the type 
    in the internal format of the backend server
    

    I guess PQbinaryTuples is true there.

    PQGetvalue() returns a char * as per the docs. (uint32_t *) will turn that char * into a pointer to an unsinged 32 bit integer, the * before that will dereference this to get the actual value (an unsigned, 32bit integer), and finally ntohl will convert that into a native 32bit integer for the platform, which presumably means that the original storing format is in network order.

    If we were to "split" that code, that would give:

    // Get value from database as a char *
    char *in_database = PQgetvalue(result, i, 0);
    // Convert the pointer to char to a pointer to an unsigned, 32bit integer
    uint32_t *ptr = (uint32_t *) in_database;
    // Dereference that pointer to obtain the actually stored value
    uint32_t stored_value = *ptr;
    // Turn that value to a native integer for the CPU
    uint32_t ip = ntohl(stored_value);
    

提交回复
热议问题