簡體   English   中英

將兩個 3 字節整數和一個 2 字節 integer 組合成一個 8 字節 integer

[英]Combine two 3 byte integers, and one 2 byte integer into one 8 byte integer

嘗試將三個整數存儲為一個以用於 hash,並解碼回其原始值。

變量:

x = 3 byte integer (Can be negative)
z = 3 byte integer (Can be negative)
y = 2 byte integer (Cannot be negative)

我當前的代碼 - 不適用於底片:

long combined = (y) | (((long) z) << 16) | ((((long) x)) << 40);
int newX = (int) (combined >> 40); // Trim off 40 bits, leaving the heading 24
int newZ = (int) ((combined << 24) >> (40)); // Trim off 24 bits left, and the 16 bits to the right
int newY = (int) ((combined << 48) >> 48); // Trim off all bits other then the first 16

它不適用於負數,因為您的“3 字節整數”或“2 字節整數”實際上是一個常規的 4 字節整數。 如果數字為負數,所有最高位將被設置為“1”; 如果你將二進制或數字放在一起,這些高 1 位將覆蓋其他數字的位。

您可以使用位掩碼正確編碼數字:

long combined = (y & 0xffff) | (((long) z & 0xffffff) << 16) | ((((long) x & 0xffffff)) << 40);

這將切斷您感興趣的 16 或 24 位范圍之外的高位。

解碼已經工作正常,因為您執行的位移處理了符號擴展。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM