Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte array to short array in C#

Tags:

c#

bytearray

I'm currently reading a file and wanted to be able to convert the array of bytes obtained from the file into a short array.

How would I go about doing this?

like image 656
williamtroup Avatar asked Jul 09 '09 15:07

williamtroup


2 Answers

Use Buffer.BlockCopy.

Create the short array at half the size of the byte array, and copy the byte data in:

short[] sdata = new short[(int)Math.Ceiling(data.Length / 2)];
Buffer.BlockCopy(data, 0, sdata, 0, data.Length);

It is the fastest method by far.

like image 50
steppenwolfe Avatar answered Sep 27 '22 22:09

steppenwolfe


One possibility is using Enumerable.Select:

byte[] bytes;
var shorts = bytes.Select(b => (short)b).ToArray();

Another is to use Array.ConvertAll:

byte[] bytes;
var shorts = Array.ConvertAll(bytes, b => (short)b);
like image 22
jason Avatar answered Sep 27 '22 22:09

jason