Ushort[] array to byte[] array

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#.

Maybe this will help you
How to convert byte[] to short[] or float[] arrays in C# (markheath.net)

@skeller

var registers = new ushort[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
var heap = Reflection.Serialize(registers, typeof(ushort));
var data = new byte[heap.Length - 3];
Array.Copy(heap, 3, data, 0, data.Length);

or just use offset 3 in the heap to avoid additional copying

2 Likes

This is brilliant. How did I not think of this!

Thanks for the suggestion. I think I will give that a try.

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

1 Like