根據文檔:
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 *
變成一個指向一個unsinged的32位整數的指針,*
在這之前將取消這個參數來得到實際值(一個無符號的32位整數),最後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);
來源
2013-01-05 15:56:12
fge
確實**意味着原始存儲格式是網絡順序**意味着像x.x.x.x這樣的類型? – smttsp
不,這意味着這個整數的原始存儲是大端。例如,IP「1.2.3.4」的編號爲「0x01020304」,在大端編碼中存儲爲「0x01,0x02,0x03,0x04」。但是,如果你的CPU架構是小端,這個相同的數字被「存儲」爲「0x04,0x03,0x02,0x01」。 'ntoh *()/ hton *()'函數系列可以將主機本身理解的東西和網絡需要的東西進行來回轉換。在大端CPU體系結構上,這些功能基本上都是noops,但在小端架構上卻不是這樣。 – fge
@tusherity請參閱編輯以獲取更完整的說明 – fge