[英]How can I store 4 8 bit coordinates into one integer (C#)?
Lets say I have the following four variables: player1X, player1Y, player2X, player2Y.假设我有以下四个变量:player1X、player1Y、player2X、player2Y。 These have, for example, respectively the following values: 5, 10, 20, 12. Each of these values is 8 bits at max and I want to store them into one integer (32 bits), how can I achieve this?例如,它们分别具有以下值:5、10、20、12。这些值中的每一个最大为 8 位,我想将它们存储到一个 integer(32 位)中,我该如何实现呢?
By doing this, I want to create a dictionary, keeping count of how often certain states have happened in the game.通过这样做,我想创建一个字典,记录游戏中某些状态发生的频率。 For example, 5, 10, 20, 12 is one state, 6, 10, 20, 12 would be another.例如,5、10、20、12 是一个 state,6、10、20、12 是另一个。
You can use BitConverter
您可以使用BitConverter
To get one Integer out of 4 bytes:要从 4 个字节中获取一个 Integer:
int i = BitConverter.ToInt32(new byte[] { player1X, player1Y, player2X, player2Y }, 0);
To get the four bytes out of the integer:要从 integer 中获取四个字节:
byte[] fourBytes = BitConverter.GetBytes(i);
To "squeeze" 4 8 bits value in a 32 bit space, you need to "shift" the bits for your various values, and add them together.要在 32 位空间中“挤压”4 个 8 位值,您需要为各种值“移动”位,并将它们相加。
The opposite operations is to "unshift" and use some modulo to get the individual numbers you need.相反的操作是“取消移位”并使用一些模来获得您需要的单个数字。
Here is an alterantive:这是一个替代方案:
Make a struct with defined packing.用定义的包装制作一个结构。 Expose:暴露:
Done.完毕。
And you can easily access and work with them WITHOUT a bitconverter et al and never have to define an array, which is expensive jsut to throw it away.而且您无需使用 bitconverter 等就可以轻松访问和使用它们,并且永远不必定义数组,这很昂贵,只是扔掉它。
You can place the values by shifting to the apropriate offset您可以通过移动到适当的偏移量来放置值
Example:例子:
// 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.