我有一個 4 位元組整數(有符號),并且(i)我想反轉位元組順序,(ii)我想將位元組(即 4 個位元組)存盤為字串的位元組。我正在使用 C 。為了反轉 Big Endian 中的位元組順序,我使用了 ntohl,但我不能使用它,因為我的數字也可能是負數。
例子:
int32_t a = -123456;
string s;
s.append(reinterpret_cast<char*>(reinterpret_cast<void*>(&a))); // int to byte
此外,當我附加這些資料時,似乎我附加了 8 個位元組而不是 4 個位元組,為什么?我需要使用附加(我不能使用 memcpy 或其他東西)。你有什么建議嗎?
uj5u.com熱心網友回復:
我使用的是 ntohl,但我不能使用它,因為我的數字也可能是負數。
目前尚不清楚為什么您認為負數會成為問題。用 . 轉換負數很好ntohl。
s.append(reinterpret_cast<char*>(reinterpret_cast<void*>(&a)));
std::string::append(char*)要求引數指向一個空終止的字串。整數不是以空值結尾的(除非它碰巧包含一個偶然表示空終止符的位元組)。由于違反了這個要求,程式的行為是未定義的。
你有什么建議嗎?
要修復此錯誤,您可以改用std::string::append(char*, size_type)多載:
s.append(reinterpret_cast<char*>(&a), sizeof a);
reinterpret_cast<char*>(reinterpret_cast<void*>
內部演員表void*是多余的。沒有什么不同的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/472698.html
標籤:C
上一篇:從陣列中查找子集
下一篇:如何遍歷具有不同型別的多個向量?
