Using SitCore I am retrieving 424 registers from a device over Modbus using a series of multiple requests. The values are stored in a ushort[424] array. I need to convert it to a byte array for various uses. Is there a quick way to do it?
I can do it with a For loop but I am curious if there is a better way.
In C I would use a Union Struct but I don’t see a way to do that with C#.
I tried @cd_work suggestion. It does go into a byte array but the byte ordering ends up wrong, or different than expected. So when I go to extract individual items using something like the following it returns the wrong value.
var speed = BitConverter.ToInt32(data, 121)
I need to dig into it a little more to understand exactly what is happening.
What is ‘groupSize’ in the BitConverter.SwapEndianness(data, groupSize) command?
Yes indeed, Serialization takes place in Big-Endian format. And here is Bit Conversion in Little-Endian format. Why this is so is not for me question.
To navigate between them use BitConverter.SwapEndianness (data, sizeof (ushort));
or BitConverter.SwapEndianness (data, 2);