![](/img/trans.png)
[英]How can I quickly and accurately multiply a 64-bit integer by a 64-bit fraction in C#?
[英]How can I store 4 8 bit coordinates into one integer (C#)?
假設我有以下四個變量:player1X、player1Y、player2X、player2Y。 例如,它們分別具有以下值:5、10、20、12。這些值中的每一個最大為 8 位,我想將它們存儲到一個 integer(32 位)中,我該如何實現呢?
通過這樣做,我想創建一個字典,記錄游戲中某些狀態發生的頻率。 例如,5、10、20、12 是一個 state,6、10、20、12 是另一個。
您可以使用BitConverter
要從 4 個字節中獲取一個 Integer:
int i = BitConverter.ToInt32(new byte[] { player1X, player1Y, player2X, player2Y }, 0);
要從 integer 中獲取四個字節:
byte[] fourBytes = BitConverter.GetBytes(i);
要在 32 位空間中“擠壓”4 個 8 位值,您需要為各種值“移動”位,並將它們相加。
相反的操作是“取消移位”並使用一些模來獲得您需要的單個數字。
這是一個替代方案:
用定義的包裝制作一個結構。 暴露:
完畢。
而且您無需使用 bitconverter 等就可以輕松訪問和使用它們,並且永遠不必定義數組,這很昂貴,只是扔掉它。
您可以通過移動到適當的偏移量來放置值
例子:
// Composing
byte x1 = ...;
byte x2 = ...;
byte x3 = ...;
byte x4 = ...;
uint x = x1 | (x2 << 0x8) | (x3 << 0x10) | (x4 << 0x18);
// Decomposing
uint x = ...;
byte x1 = x & 0xFF;
byte x2 = (x >> 0x8) & 0xFF;
byte x3 = (x >> 0x10) & 0xFF;
byte x4 = (x >> 0x18) & 0xFF;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.