简体   繁体   中英

How to convert from UInt32 array to byte array?

This question only vise versa. For now I got this:

UInt32[] target;

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

And this doesn't work, I get array filled with 0x00 .

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

I would recommend something like the following:

UInt32[] target;

//Assignments

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

See code:

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

Also see:

Try this code. It works for me.

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

You need to multiple by 4 to create your byte array, since UInt32 is 4 bytes (32 bit). But use BitConverter and fill a list of byte and late you can create an array out of it if you need.

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

If you need array then:

byte[] decoded = listOfBytes.ToArray();

Your code has a few errors:

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

This should yield what you're expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM