繁体   English   中英

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

[英]Convert ushort[] into byte[] and back

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

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

Ushort数组

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

字节数组

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

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

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

谢谢。

您正在寻找BlockCopy

https://msdn.microsoft.com/en-us/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);

使用offset s( Buffer.BlockCopy第二个第四个参数),您可以将1D数组分解 (正如您所说):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM