C# 将ushort[]转换为字节[]并返回

C# 将ushort[]转换为字节[]并返回,c#,arrays,byte,ushort,C#,Arrays,Byte,Ushort,我有一个ushort数组,需要转换成字节数组才能通过网络传输 一旦它到达目的地,我需要将它重新转换回它要使用的ushort数组 Ushort数组 是长度为217088的数组(分解图像512乘以424的1D数组)。它存储为16位无符号整数。每个元素是2个字节 字节数组 出于网络目的,需要将其转换为字节数组。由于每个ushort元素值2个字节,我假设字节数组长度需要为217088*2 在转换方面,然后正确地“取消转换”,我不确定如何做到这一点 这适用于C#中的Unity3D项目。有人能给我指出正确的

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

一旦它到达目的地,我需要将它重新转换回它要使用的ushort数组

Ushort数组

是长度为217088的数组(分解图像512乘以424的1D数组)。它存储为16位无符号整数。每个元素是2个字节

字节数组

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

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

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


谢谢。

您正在寻找
区块拷贝

是的,
short
以及
ushort
的长度为2字节;这就是为什么对应的
byte
数组应该比初始
short
one长两倍

直接(
byte
short
):

反向:

  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数组(如您所说):

//我不清楚什么是“分解的1d数组”,所以
//让它成为一个数组(比如512行,每行424项)
ushort[][]图像=。。。;
//数据-将所有长度(512*424)和*2(字节)相加
字节[]数据=新字节[image.Sum(line=>line.Length)*2];
整数偏移=0;
对于(int i=0;i
谢谢您的帮助。你能解释一下{5,6}和{7,8}到底在做什么吗?谢谢。@Oliver Jone:
{5,6}
只是示例值:
新字节[]{5,6}
-创建一个新的字节数组,其中包含两项-
5
6
。为此,我想指出,您可能需要使用
Buffer.BlockCopy(图像[i],0,数据,偏移量,计数)执行多维数组复制时(0是for循环重复时每个数组的起始位置)
  short[] source = new short[] {7, 8};
  byte[] target = new byte[source.Length * 2]; 
  Buffer.BlockCopy(source, 0, target, 0, source.Length * 2);
  // 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;
  }