Convert ushort[] into byte[] and back
Asked Answered
L

1

6

I have a ushort array that needs converting into a byte array to be transferred over a network.

Once it gets to its destination, I need then reconvert it back into the same ushort array it was to being with.

Ushort Array

Is an array that is of Length 217,088 (1D array of broken down image 512 by 424). It's stored as 16-bit unsigned integers. Each element is 2 bytes.

Byte Array

It needs to be converted into a byte array for network purposes. As each ushort element is worth 2 bytes, I assume the byte array Length needs to be 217,088 * 2?

In terms of converting, and then 'unconverting' correctly, I am unsure on how to do that.

This is for a Unity3D project that is in C#. Could someone point me in the right direction?

Thanks.

License answered 13/5, 2016 at 15:24 Comment(0)
O
6

You're looking for BlockCopy:

https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.110).aspx

and yes, short as well as ushort is 2 bytes long; and that's why corresponding byte array should be two times longer than initial short one.

Direct (byte to short):

  byte[] source = new byte[] { 5, 6 };
  short[] target = new short[source.Length / 2 + source.Length % 2];

  Buffer.BlockCopy(source, 0, target, 0, source.Length);

Reverse:

  short[] source = new short[] {7, 8};
  byte[] target = new byte[source.Length * 2]; 
  Buffer.BlockCopy(source, 0, target, 0, source.Length * 2);

using offsets (the second and the fourth parameters of Buffer.BlockCopy) you can have 1D array being broken down (as you've put it):

  // it's unclear for me what is the "broken down 1d array", so 
  // let it be an array of array (say 512 lines, each of 424 items)
  ushort[][] image = ...;

  // data - sum up all the lengths (512 * 424) and * 2 (bytes)
  byte[] data = new byte[image.Sum(line => line.Length) * 2];

  int offset = 0;

  for (int i = 0; i < image.Length; ++i) {
    int count = image[i].Length * 2;

    Buffer.BlockCopy(image[i], offset, data, offset, count);

    offset += count;
  }
Otho answered 13/5, 2016 at 15:33 Comment(5)
Thanks for this. May you explain what the '{ 5, 6 }' and '{7, 8}' are doing exactly? Thanks.License
@Oliver Jone: { 5, 6 } are just sample values: new byte[] { 5, 6 }; - creates a new array of byte with two items - 5 and 6.Otho
Thanks for this, just wanted to point out that you may need to use Buffer.BlockCopy(image[i], 0, data, offset, count); when doing a multidimensional array copy (0 being the starting position of each array as the for loop repeats)Statehood
When converting from byte[] to short[] and byte array Length is odd, the length of short array must be adjusted. Change target initialisation to new short[source.Length / 2 + source.Length % 2];Aerugo
@Arci: you are quite right, thank you! To be on the safer side of the road source.Length % 2 is required.Otho

© 2022 - 2024 — McMap. All rights reserved.