![](/img/trans.png)
[英]What happens when accessing an array with multiple different types: int16_t, int, and int64_t, in C++?
[英]Convert C++ type int16_t to int64_t without modifying the underlying binary
我正在嘗試為3D空間中的對象生成哈希碼,以便可以使用二進制搜索算法在數組中快速找到它。
由於此數組中的每個對象都有一個唯一的XYZ位置,因此我認為可以使用這三個值來生成哈希碼。 我使用以下代碼嘗試生成哈希代碼。
int64_t generateCode(int16_t x, int16_t y, int16_t z) {
int64_t hashCode = z;//Set Z bits.
hashCode <<= 16;//Shift them 16 bits.
hashCode |= y;//Set Y bits.
hashCode <<= 16;//Shift them 16 bits.
hashCode |= x;//Set X bits.
}
現在這就是我所知道的問題。 考慮以下代碼安全性:
int16_t x = -1;
cout << "X: " << bitset<16>(x) << endl;//Prints the binary value of X.
int64_t y = x;//Set Y to X. This will automatically cast the types.
cout << "Y: " << bitset<64>(y) << endl;//Prints the binary value of Y.
該程序的輸出如下:
X: 1111111111111111
Y: 1111111111111111111111111111111111111111111111111111111111111111
它保留數字的數值,但更改基礎二進制文件即可。 我不想修改該二進制文件,因此可以得到如下輸出:
X: 1111111111111111
Y: 0000000000000000000000000000000000000000000000001111111111111111
這樣,我便可以根據XYZ值創建唯一的哈希碼,如下所示:
Unused X Y Z
HashCode: [0000000000000000][0000000000000000][0000000000000000][0000000000000000]
這將用於二進制搜索。
大多數編譯器將理解並優化它以執行您實際想要的操作:
int16_t a[4] = { 0, z, y, x };
int64_t res;
memcpy(&res, a, sizeof(res));
(編譯器將理解memcpy
可以通過簡單的64位內存操作來完成,而不是實際調用真正的memcpy
)
首先將int16_t
轉換為uint16_t
,然后將它們合並到uint64_t
,最后將其轉換為int64_t
:
int64_t generateCode(int16_t x, int16_t y, int16_t z) {
uint64_t hashCode = static_cast<uint16_t>(z);
hashCode <<= 16;
hashCode |= static_cast<uint16_t>(y);
hashCode <<= 16;
hashCode |= static_cast<uint16_t>(x);
return static_cast<int64_t>(hashCode);
}
int16_t
/ int64_t
類型將是二進制補碼表示形式(C標准的7.2.1.1第1節要求這樣做),因此將它們轉換為相同大小的uint*_t
將是按位無操作的。
嘗試int64_t y = (uint16_t) x;
這是什么,它將確保添加的額外位是0而不是1,因為這是無符號的。 但是請確保您檢查符號位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.