繁体   English   中英

ntohl(*(uint32_t *)…)做什么?

[英]what does ntohl(*(uint32_t*) …)do?

ip=ntohl(*(uint32_t*)PQgetvalue(result, i, 0));

该代码段的含义是什么?

我的猜测是该代码从PostgreSQL数据库中输入(其类型为uint32_t )并将其转换为IP格式(例如192.168.xx

我的猜测正确吗? 如果不是,那是什么意思?

注意:根据http://linux.die.net/man/3/ntohl

ntohl()函数将无符号整数netlong从网络字节顺序转换为主机字节顺序。

另外,有人可以解释*(uint32_t*)作用吗?

ntohl意思是“长期托管网络”。 它(大概)将整数类型从网络(大端)转换为主机字节顺序。 但是,如果您不熟悉计算机的耐用性,请小心使用此方法。 如果您使用的是ntohl格式的计算机,并且已对低端格式的数据(即未以大端格式发送的数据)使用ntohl ,则可能会遇到问题。

*(unit32_t*)是对32位无符号整数指针( (unit32_t*)部分)的(unit32_t*) ,然后前面的*是该指针上的取消引用运算符。

编辑

正如njr在下面的评论中指出的那样,这是关于忍耐性的良好参考: http : //en.wikipedia.org/wiki/Endianness

根据文档:

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位整数的指针,在此之前的*将取消引用它以获得实际值(一个无符号的32bit整数),最后ntohl将其转换为一个32位整数对于平台,这大概意味着原始存储格式是网络顺序。

如果我们要“拆分”该代码,则会得到:

// 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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