vote up 0 vote down
star
1

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?

flag
3 
Do you want to convert 1 byte to 1 short, or 2 bytes to 1 short? – mpbloch 2 days ago
add comment

3 Answers

vote up 5 vote down
check

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);
link|flag
Your original suggestion (before you added the second one later on) is rather inefficient – activa 2 days ago
add comment
vote up 0 vote down
 short[] wordArray = Array.ConvertAll(byteArray, (b) => (short)b);
link|flag
add comment
vote up -1 vote down
byte[] bytes;
var shorts = bytes.Select(n => System.Convert.ToInt16(n)).ToArray();
link|flag
That's extremely inefficient: Calling convert.ToInt16() for every element, storing it in a temporary list, and then copying it to an new array. – activa 2 days ago
yes, it is inefficient. I'm thinking that it's safer, tho, then casting. – Chris 2 days ago
Safer than casting? A cast of byte to short always works. It can never throw an exception – activa 2 days ago
add comment

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.