在C#中将整数存储在字节数组中

3

我是一个小项目的开发者,需要将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;

我改变了第一个值的位,但现在不确定如何将其检索回来...进行相反的过程。

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


6
使用 BitConverter.GetBytes(...) 方法来进行编码,使用 BitConverter.ToInt32(...) 方法来进行解码。 - user6522773
@x... 但我需要在这个数组中插入4个字节。抱歉,我编辑了我的问题。BitConvertor 返回一个新的字节数组,我不想让它更复杂,并且为了合并从 BitConvertor 得到的两个 4 字节[] 数组。 - Slashy
1
你是指这个吗?int b = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3] - Lasse V. Karlsen
@LasseV.Karlsen 太棒了。你应该把它写成答案:0 - Slashy
3个回答

4

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

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

这里有一个.NET Fiddle演示了相关的IT技术。


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

取决于您的评论回复,您可以这样做:

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();

1
这正是我不想做的。没有简单的位操作或其他解决方案吗?@x...我也在寻找...效率问题...这是为实时程序准备的...我真的很想使用底层的东西。 - Slashy
1
位移操作不仅与C/C++有关.. 哈哈 - Slashy
@Slashy - 你真的在做这个时遇到了性能问题吗?这是一个非常快速的计算。 - Enigmativity
就像这样:有一枚火箭要飞往月球,而@Slashy却想先学习如何骑自行车...:=) - user6522773
火箭的比喻并不差,因为用火箭去开往下一个商店可能有点过头了,与此相比,使用自行车更合适。此外,位移也并不是那么复杂。当在不同系统之间交换数据时,使用BitConverter可能会导致字节序问题。 - v01pe
显示剩余6条评论

1
你可以使用 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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接