Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert byte array to UInt32 array?

Lets say In C++ I got code like this..

void * target
uint32 * decPacket = (uint32 *)target;

So in C# it would be like..

byte[] target;
UInt32[] decPacket = (UInt32[])target;

Cannot convert type byte[] to uint[]

How do I convert this memory aligning thing C++ does to arrays to C#?

like image 414
SSpoke Avatar asked Sep 02 '11 20:09

SSpoke


People also ask

How do I convert an image to a Bytearray?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

How do you convert int to Bytearray?

When you want to convert an int value to a byte array, you can use the static method ByteArray. toByteArray(). This method takes an int input and returns a byte array representation of the number.

Which of the following ways is correct to convert a byte into long object?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).

Which of the following converts an array of bytes to an instance of class class?

Indirection Struct. It is possible to read byte array as struct in C#: Reading a C/C++ data structure in C# from a byte array You could then create a class instance from that struct.


2 Answers

Well, something close would be to use Buffer.BlockCopy:

uint[] decoded = new uint[target.Length / 4];
Buffer.BlockCopy(target, 0, decoded, 0, target.Length);

Note that the final argument to BlockCopy is always the number of bytes to copy, regardless of the types you're copying.

You can't just treat a byte array as a uint array in C# (at least not in safe code; I don't know about in unsafe code) - but Buffer.BlockCopy will splat the contents of the byte array into the uint array... leaving the results to be determined based on the endianness of the system. Personally I'm not a fan of this approach - it leaves the code rather prone to errors when you move to a system with a different memory layout. I prefer to be explicit in my protocol. Hopefully it'll help you in this case though.

like image 102
Jon Skeet Avatar answered Oct 08 '22 17:10

Jon Skeet


You can have the cake (avoid allocations) and eat it too (avoid iterations), if you're willing to move to the dark side.

Check out my answer to a related question, in which I demonstrate how to convert float[] to byte[] and vice versa: What is the fastest way to convert a float[] to a byte[]?

like image 26
Omer Mor Avatar answered Oct 08 '22 18:10

Omer Mor