簡體   English   中英

將ushort []轉換為byte []並返回

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

我有一個ushort數組,需要轉換成一個字節數組,通過網絡傳輸。

一旦到達目的地,我需要將其重新轉換回與之相同的ushort陣列。

Ushort數組

是一個長度為217,088的數組(1D陣列的故障圖像512乘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

是的, shortushort長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 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