什么ntohl(*(uint32_t *)...)? [英] what does ntohl(*(uint32_t*) ...)do?
问题描述
ip=ntohl(*(uint32_t*)PQgetvalue(result, i, 0));
此代码段的意义是什么?
What is the meaning of this code segment?
我的猜测是,这段代码从PostgreSQL数据库(它的类型是 uint32_t
)输入,并将其转换为IP格式(例如 192.168。 xx
)
My guess is that this code takes an input from PostgreSQL database (its type is uint32_t
) and converts it to IP format (e.g. 192.168.x.x
)
我的猜测是否正确?
注意:根据 http://linux.die.net/man/3/ntohl :
ntohl()
函数将无符号整数netlong从网络字节顺序转换为主机字节顺序。
The
ntohl()
function converts the unsigned integer netlong from network byte order to host byte order.
Also, could somebody explain what *(uint32_t*)
does?
推荐答案
p>根据文档:
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
我想 PQbinaryTuples
是真的。
PQGetvalue()
返回 char *
文档。 (uint32_t *)
会将 char *
变成指向未读取的32位整数的指针, *
之前,将取消引用此值以获取实际值(无符号,32位整数),最后 ntohl
32位整数的平台,这可能意味着原始的存储格式是在网络顺序。
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.
如果我们拆分该代码,那将给: p>
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);
这篇关于什么ntohl(*(uint32_t *)...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!