0

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

UInt32[] target;

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

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

4

5 回答 5

3

您可以使用BitConverter.GetBytes方法将 a 转换unitbyte

于 2013-10-08T19:04:54.130 回答
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();

另见:

于 2013-10-08T19:16:33.940 回答
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);
    }
于 2013-10-08T19:15:09.613 回答
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();
于 2013-10-08T19:09:33.480 回答
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.
);

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

于 2013-10-08T19:11:58.557 回答