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

查看:67
本文介绍了如何将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天全站免登陆