我在做一个小项目,我需要在字节数组中存储 4 个 int
类型(稍后将在套接字上发送)。
这是代码:
int a = 566;
int b = 1106;
int c = 649;
int d = 299;
byte[] bytes = new byte[16];
bytes[0] = (byte)(a >> 24);
bytes[1] = (byte)(a >> 16);
bytes[2] = (byte)(a >> 8);
bytes[3] = (byte)a;
我移动了第一个值的位,但我现在不确定如何取回它...执行相反的过程。
我希望我的问题很清楚,如果我遗漏了什么,我会很乐意再次解释。 谢谢。
最佳答案
要从字节数组中提取出 Int32
,请使用以下表达式:
int b = bytes[0] << 24
| bytes[1] << 16
| bytes[2] << 8
| bytes[3]; // << 0
这是一个.NET Fiddle这表明。
关于C# 将 int 存储在字节数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38180076/