简体   繁体   English

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

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

I have a ushort array that needs converting into a byte array to be transferred over a network. 我有一个ushort数组,需要转换成一个字节数组,通过网络传输。

Once it gets to its destination, I need then reconvert it back into the same ushort array it was to being with. 一旦到达目的地,我需要将其重新转换回与之相同的ushort阵列。

Ushort Array Ushort数组

Is an array that is of Length 217,088 (1D array of broken down image 512 by 424). 是一个长度为217,088的数组(1D阵列的故障图像512乘424)。 It's stored as 16-bit unsigned integers. 它存储为16位无符号整数。 Each element is 2 bytes. 每个元素是2个字节。

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? 由于每个ushort元素值2个字节,我假设字节数组长度需要为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#. 这适用于C#中的Unity3D项目。 Could someone point me in the right direction? 有人能指出我正确的方向吗?

Thanks. 谢谢。

You're looking for BlockCopy : 您正在寻找BlockCopy

https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.110).aspx 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; 是的, shortushort长2个字节; and that's why corresponding byte array should be two times longer than initial short one. 这就是为什么相应的byte数组应该比初始short数组长两倍。

Direct ( byte to short ): 直接( byteshort ):

  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 offset s (the second and the fourth parameters of Buffer.BlockCopy ) you can have 1D array being broken down (as you've put it): 使用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