如何从UInt32数组转换为字节数组?

时间:2013-10-08 19:01:29

标签: c# arrays

This问题反之亦然。现在我得到了这个:

UInt32[] target;

byte[] decoded = new byte[target.Length * 2];
Buffer.BlockCopy(target, 0, decoded, 0, target.Length);

这不起作用,我将数组填满0x00

5 个答案:

答案 0 :(得分:3)

您可以使用BitConverter.GetBytes方法将unit转换为byte

答案 1 :(得分:3)

我会推荐以下内容:

UInt32[] target;

//Assignments

byte[] decoded = new byte[target.Length * sizeof(uint)];
Buffer.BlockCopy(target, 0, decoded, 0, decoded.Length);

参见代码:

uint[] target = new uint[] { 1, 2, 3 };

//Assignments

byte[] decoded = new byte[target.Length * sizeof(uint)];
Buffer.BlockCopy(target, 0, decoded, 0, decoded.Length);

for (int i = 0; i < decoded.Length; i++)
{
    Console.WriteLine(decoded[i]);
}

Console.ReadKey();

另见:

答案 2 :(得分:2)

试试这段代码。它对我有用。

UInt32[] target = new UInt32[]{1,2,3}; 
  byte[] decoded = new byte[target.Length * sizeof(UInt32)];
  Buffer.BlockCopy(target, 0, decoded, 0, target.Length*sizeof(UInt32));

    foreach(byte b in decoded)     
    {
        Console.WriteLine( b);
    }

答案 3 :(得分:1)

您需要多个4来创建byte数组,因为UInt32是4个字节(32位)。但是使用BitConverter并填写byte列表,如果需要,可以稍后创建一个数组。

UInt32[] target = new UInt32[] { 1, 2, 3 };
byte[] decoded = new byte[target.Length * 4]; //not required now
List<byte> listOfBytes = new List<byte>();
foreach (var item in target)
{
    listOfBytes.AddRange(BitConverter.GetBytes(item));   
}

如果你需要数组:

byte[] decoded = listOfBytes.ToArray();

答案 4 :(得分:1)

您的代码有一些错误:

UInt32[] target = new uint[] { 1, 2, 3, 4 };

// Error 1:
// You had 2 instead of 4.  Each UInt32 is actually 4 bytes.
byte[] decoded = new byte[target.Length * 4];

// Error 2:
Buffer.BlockCopy(
  src: target, 
  srcOffset: 0, 
  dst: decoded,
  dstOffset: 0, 
  count: decoded.Length // You had target.Length. You want the length in bytes.
);

这应该会产生你所期待的。