ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-10-13 04:07:07  阅读:197  来源: 互联网

标签:c pointers type-conversion


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

该代码段的含义是什么?

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

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

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

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

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

解决方法:

根据文档:

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

标签:c,pointers,type-conversion
来源: https://codeday.me/bug/20191013/1905274.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有