简体   繁体   中英

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

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 PostgreSQL database (its type is uint32_t ) and converts it to IP format (eg 192.168.xx )

Is my guess correct? If not, what does it mean?

Note: According to http://linux.die.net/man/3/ntohl :

The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.

Also, could somebody explain what *(uint32_t*) does?

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 (ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM