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#?
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.
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.
The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).
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.
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.
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[]?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With