gpt4 book ai didi

c# - C#中如何将字节数组表示的Int32数组转化为Int32数组

转载 作者:行者123 更新时间:2023-11-30 20:32:34 29 4
gpt4 key购买 nike

我有一个由字节数组表示的 Int32 数组(每 4 个字节是 1 个 Int32),我想将它们转换为 Int32 数组(长度为 Byte.length/4)。这是我想要的示例:

//byte[] buffer;
for (int i=0; i<buffer.Length; i+=4)
{
Int32 temp0 = BitConverter.ToInt32(buffer, i);
temp0 += 10;
byte[] temp1 = BitConverter.GetBytes(temp0);
for (int j=0;j<4;j++)
{
buffer[i + j] = temp1[j];
}
}

但我不想复制它们,我只是想能够告诉编译器它是 Int32 数组而不是字节数组(以便以后进行操作)。

我看了这个How to Convert a byte array into an int array但它将每个字节转换为 Int32,我想将每个 4 字节转换为 Int32。我也希望不将其复制到另一个数组中以提高性能。

(我们可以假设硬件是 native 字节序,用于小端表示的小端系统)。

最佳答案

没有直接的方法可以在不复制它们的情况下转换它们。您可以编写一个 linq 查询以将字节作为整数返回,但这不会让您操纵它们。

实现您想要的一种方法是将其包装在自己的类中:

public class IntArrayOverBytes
{
private readonly byte[] bytes;
public IntArrayOverBytes(byte[] bytes)
{
this.bytes = bytes;
}

public int this[int index]
{
get { return BitConverter.ToInt32(bytes, index * 4); }
set { Array.Copy(BitConverter.GetBytes(value), 0, bytes, index * 4, 4); }
}
}

通过这个类(class)你可以阅读int来自您的 byte 的值数组并将它们写回:

IntArrayOverBytes intArray = new IntArrayOverBytes(bytes);
intArray[5] = 2016;
Console.WriteLine(intArray[5]);

完整Array像功能一样,您需要添加更多代码。例如实现 IEnumerable<int>可能有用:

public int Length => bytes.Length/4;
public IEnumerator<int> GetEnumerator()
{
for(int i=0; i<Length; i++) yield return this[i];
}

关于c# - C#中如何将字节数组表示的Int32数组转化为Int32数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227230/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com