将ushort []转换为byte []并返回

时间:2016-05-13 15:24:21

标签: c# arrays byte ushort

我有一个ushort数组,需要转换为一个字节数组,以便通过网络传输。

一旦到达目的地,我需要将其重新转换回与之相同的ushort数组。

Ushort数组

是一个长度为217,088的数组(1D数组的故障图像512乘424)。它存储为16位无符号整数。每个元素都是2个字节。

字节数组

需要将其转换为字节数组以用于网络目的。由于每个ushort元素值2个字节,我假设字节数组长度需要为217,088 * 2?

在转换方面,然后正确地“转换”方面,我不确定如何做到这一点。

这适用于C#中的Unity3D项目。有人能指出我正确的方向吗?

感谢。

1 个答案:

答案 0 :(得分:3)

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

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