首页 文章

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

提问于
浏览
3

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

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

Ushort Array

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

Byte Array

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

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

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

谢谢 .

1 回答

  • 2

    您正在寻找 BlockCopy

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

    是的, short 以及 ushort 是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);
    

    使用 offsetBuffer.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;
      }
    

相关问题