views:

1852

answers:

6

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?

+6  A: 

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);
Jason
Your original suggestion (before you added the second one later on) is rather inefficient
Philippe Leybaert
Another option would be bytes.Cast<short>().ToArray();
Joel Mueller
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 http://stackoverflow.com/questions/445471/puzzling-enumerable-cast-invalidcastexception.
Jason
A: 
 short[] wordArray = Array.ConvertAll(byteArray, (b) => (short)b);
Philippe Leybaert
A: 
byte[] bytes;
var shorts = bytes.Select(n => System.Convert.ToInt16(n)).ToArray();
Muad'Dib
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
yes, it is inefficient. I'm thinking that it's safer, tho, then casting.
Muad'Dib
Safer than casting? A cast of byte to short always works. It can never throw an exception
Philippe Leybaert
+1  A: 

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))

(who like short shorts... :D)
This doesn't work. You have to do it like this to make it work: short s = (short)((bytes[0] << 8) | bytes[1]);
DaveN59
A: 
short value = BitConverter.ToInt16(bytes, index);
Gabriel
A: 

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);

steppenwolfe