如何将 4 个 8 位坐标存储为一个整数(C#)? [英] How can I store 4 8 bit coordinates into one integer (C#)?

查看:25
本文介绍了如何将 4 个 8 位坐标存储为一个整数(C#)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下四个变量:player1X、player1Y、player2X、player2Y.例如,它们分别具有以下值:5、10、20、12.这些值中的每一个最多为 8 位,我想将它们存储为一个整数(32 位),我该如何实现?

通过这样做,我想创建一个字典,记录游戏中某些状态发生的频率.例如,5、10、20、12 是一种状态,6、10、20、12 是另一种状态.

解决方案

可以使用BitConverter

从 4 个字节中获取一个整数:

int i = BitConverter.ToInt32(new byte[] { player1X, player1Y, player2X, player2Y }, 0);

从整数中取出四个字节:

byte[]fourBytes = BitConverter.GetBytes(i);

Lets say I have the following four variables: 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?

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.

解决方案

You can use BitConverter

To get one Integer out of 4 bytes:

int i = BitConverter.ToInt32(new byte[] { player1X, player1Y, player2X, player2Y }, 0);

To get the four bytes out of the integer:

byte[] fourBytes = BitConverter.GetBytes(i);

这篇关于如何将 4 个 8 位坐标存储为一个整数(C#)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆