我有一个 ushort 数组,需要转换为字节数组才能通过网络传输。
一旦到达目的地,我需要将其重新转换回原来的 ushort 数组。
Ushort 数组
是一个长度为 217,088 的数组(分解图像 512 x 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
是的,
short
以及ushort
都是2个字节长;这就是为什么相应的 byte
数组应该比初始 short
长两倍。
直接(
byte
至 short
):
byte[] source = new byte[] { 5, 6 };
short[] target = new short[source.Length / 2 + 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;
}