Convert byte array to short array in C?

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, be => (short)b).

Your original suggestion (before you added the second one later on) is rather inefficient – Philippe Leybaert Jul 9 '09 at 15:35 Another option would be bytes.Cast().ToArray(); – Joel Mueller Aug 9 '09 at 4:04 Actually, this results in a InvalidCastException. The short explanation is that this code implicitly causes an boxed byte to be unboxed to a short which is not a valid unboxing operation. For details, see stackoverflow.com/questions/445471/….– Jason Aug 19 '09 at 6:56.

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 shortdataLen / 2; Buffer. BlockCopy(data, x, sdata, 0, dataLen).

Short wordArray = Array. ConvertAll(byteArray, (b) => (short)b).

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)(bytes0 | (bytes1 >> 8)).

(who like short shorts... :D) – Gusman Aug 9 '09 at 0:33 This doesn't work. You have to do it like this to make it work: short s = (short)((bytes0.

Byte bytes; var shorts = bytes. Select(n => System.Convert. ToInt16(n)).ToArray().

That's extremely inefficient: Calling convert. ToInt16() for every element, storing it in a temporary list, and then copying it to an new array. – Philippe Leybaert Jul 9 '09 at 15:30 yes, it is inefficient.

I'm thinking that it's safer, tho, then casting. – Muad'Dib Jul 9 '09 at 16:09 Safer than casting? A cast of byte to short always works.It can never throw an exception – Philippe Leybaert Jul 9 '09 at 16:24.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions