簡體   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