将ushort[]转换为byte[],并且再将其转换回去

5
我有一个ushort数组,需要转换成byte数组以便通过网络传输。
一旦到达目的地,我需要将其重新转换回相同的ushort数组。
Ushort Array
是一个长度为217,088的数组(512乘以424的一维图像分解数组)。它存储为16位无符号整数。每个元素为2个字节。
Byte Array
需要将其转换为字节数组进行网络传输。由于每个ushort元素值为2个字节,因此我假设byte数组长度需要为217,088*2?
在进行正确的转换和“反转换”方面,我不确定如何操作。
这是一个使用C#编写的Unity3D项目。有谁可以指点我正确的方向吗?
谢谢。
1个回答

6
您正在寻找“BlockCopy”:
请参考以下链接:https://msdn.microsoft.com/zh-cn/library/system.buffer.blockcopy(v=vs.110).aspx 是的,shortushort都是2个字节长;因此相应的byte数组应该比初始的short数组长两倍。
直接(从byteshort):
  byte[] source = new byte[] { 5, 6 };
  short[] target = new short[source.Length / 2];

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

翻转:

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

使用Buffer.BlockCopy的第二个和第四个参数offset,你可以将一维数组分解(正如你所说的):

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

谢谢您。您能解释一下 '{ 5, 6 }' 和 '{7, 8}' 到底是做什么的吗?谢谢。 - Oliver Jones
@Oliver Jone:{ 5, 6 } 只是示例值new byte[] { 5, 6 }; - 创建一个包含两个元素 56 的新字节数组。 - Dmitry Bychenko
谢谢您,我只是想指出,在进行多维数组复制时,您可能需要使用Buffer.BlockCopy(image[i], 0, data, offset, count);(0是每个数组的起始位置,因为for循环重复)。 - Snouto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接