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
ntohl
means "network to host long." It (presumably) converts an integer type from network (big-endian) to host byte ordering. Be careful when using this method, however, if you are unfamiliar with the endianess of your machine. If you have a little-endian machine and use ntohl
on data which is already in little-endian format (i.e. wasn't sent in big-endian or otherwise) you may have problems.
*(unit32_t*)
is a casting to a 32-bit unsigned integer pointer (the (unit32_t*)
part) and then the preceeding *
is the dereference operator on that pointer.
EDIT
Here is a good reference for endianess as pointed out in the comments below by njr: http://en.wikipedia.org/wiki/Endianness
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);