2016-05-13 74 views
2

我有一个ushort数组,需要转换成字节数组才能通过网络传输。将ushort []转换为byte []并返回

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

USHORT阵列

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

字节数组

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

就转换而言,然后'正确转换',我不确定如何做到这一点。

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

谢谢。

回答

1

您正在寻找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); 

使用offset秒(Buffer.BlockCopy第四参数)可以具有一维数组是细分(如你所知):

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

感谢您的支持。你能否解释一下'{5,6}'和'{7,8}'究竟在做什么?谢谢。 –

+0

@Oliver Jone:'{5,6}'只是*样本值*:'new byte [] {5,6};' - 创建一个包含两个项目的新数组 - '5'和'6'。 –

+0

谢谢你,只是想指出你可能需要使用'Buffer.BlockCopy(image [i],0,data,offset,count);'当做一个多维数组拷贝时(0是每个数组的起始位置数组作为for循环重复) – Snouto