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

本文关键字:数组 字节 字节数 转换 UInt32 | 更新日期: 2023-09-27 18:34:31

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

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

这不起作用,我得到的数组充满了0x00.

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

我会推荐如下内容:

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

另请参阅:

  • 值的大小
  • 国际数组到字节数组
  • 块复制 MSDN
您可以使用

BitConverter.GetBytes方法将unit转换为byte

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

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);
    }
您需要

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

您的代码有几个错误:

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

这应该会产生您所期望的。