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?
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?
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);
short[] wordArray = Array.ConvertAll(byteArray, (b) => (short)b);
byte[] bytes;
var shorts = bytes.Select(n => System.Convert.ToInt16(n)).ToArray();
Hey, a short is compound of two bytes, if he's writting to the file all the shorts as true shorts, those conversions are wrong.. you must use two bytes to get the true short value, using something like
short s = (short)(bytes[0] | (bytes[1] >> 8))
use Buffer.BlockCopy create the short array at half size of byte array, then copy byte data in, the fastest method by far: short[] sdata = new short[dataLen / 2]; Buffer.BlockCopy(data, x, sdata, 0, dataLen);