位操作- c#在字节数组中存储int

本文关键字:数组 存储 int 字节数 字节 位操作 | 更新日期: 2023-09-27 17:54:21

我在一个小项目上工作,我需要在字节数组中存储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;

我移动了第一个值的位,但我不确定现在如何检索它回来…执行相反的过程

我希望我的问题是清楚的,如果我遗漏了什么,我很乐意再解释一遍。谢谢。

位操作- c#在字节数组中存储int

要从字节数组中取出Int32,使用以下表达式:

int b = bytes[0] << 24
      | bytes[1] << 16
      | bytes[2] << 8
      | bytes[3]; // << 0

下面是一个。net Fiddle演示。

根据你的评论回复,你可以这样做:

int a = 10;
byte[] aByte = BitConverter.GetBytes(a);
int b = 20;
byte[] bByte = BitConverter.GetBytes(b);
List<byte> listOfBytes = new List<byte>(aByte);
listOfBytes.AddRange(bByte);
byte[] newByte = listOfBytes.ToArray();

您可以使用MemoryStream封装字节数组,然后使用BinaryWriter向数组写入项,使用BinaryReader从数组中读取项。

示例代码:

int a = 566;
int b = 1106;
int c = 649;
int d = 299;
// Writing.
byte[] data = new byte[sizeof(int) * 4];
using (MemoryStream stream = new MemoryStream(data))
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write(a);
    writer.Write(b);
    writer.Write(c);
    writer.Write(d);
}
// Reading.
using (MemoryStream stream = new MemoryStream(data))
using (BinaryReader reader = new BinaryReader(stream))
{
    a = reader.ReadInt32();
    b = reader.ReadInt32();
    c = reader.ReadInt32();
    d = reader.ReadInt32();
}
// Check results.
Trace.Assert(a == 566);
Trace.Assert(b == 1106);
Trace.Assert(c == 649);
Trace.Assert(d == 299);