Convert a byte array to a short array?

• Question

• I have the following code that reads a number of bytes into an array then copies them into an array of shorts.

// nInt16 is the number of 16 bit integers in being read in the form of bytes

byte[] data = br.ReadBytes(nInt16 * 2);
short[] arrInt16 = new short[nInt16];
Buffer.BlockCopy(data, 0, arrInt16, 0, nInt16 * 2);

Is there a way, in C#, to read the data into a byte array and then "point" an array of short to it instead of copying the data? Similar to what can be done in C++. (I realize that arrays in C# and C++ are totally different data structrures)

Thanks.

David

Wednesday, February 14, 2007 1:55 AM

All replies

• Hi,

I don't think you can do that, it kinds of go against "type safe"

May be you can use br.ReadInt16, but you will have to read it one by one.

Wednesday, February 14, 2007 3:14 AM
• Hmmm...

I was hoping that I was missing something, but I believe that you are correct.

It is probably much more efficient to do one read and then a block copy than to read each value in individually.

Thanks.

David

Wednesday, February 14, 2007 3:53 PM
• Have you tried:

BitConverter.ToInt16(); function?

Best Regards,

Rizwan aka RizwanSharp

• Proposed as answer by Wednesday, August 24, 2011 6:07 PM
• Unproposed as answer by Wednesday, August 24, 2011 6:07 PM
Wednesday, February 14, 2007 5:46 PM
• That converts a single 16 bit integer. I have a block of data that I read into a byte array. I need to convert the byte array to an array of Int16.

Thanks.

David

Wednesday, February 14, 2007 5:56 PM
•  david2929 wrote:
 That converts a single 16 bit integer. I have a block of data that I read into a byte array. I need to convert the byte array to an array of Int16. Thanks. David

You need a loop through that array and get forward with 2 step. I mean increment index by i+2 not by i++ and then move ahead untill length of byte array is reached.

Need more help or code?

I hope you'll be successful if you give it a try. Anyways, You can always come back if you face any problem.

Best Regards & Best of Luck,

Rizwan aka RizwanSharp

• Proposed as answer by Wednesday, August 24, 2011 6:07 PM
Wednesday, February 14, 2007 6:01 PM
• Yes, I could do that...

I do not know for sure, but somehow it seems that there is less overhead copying the array one time (with BlockCopy()) and accessing it as an array of Int16, than looping through and converting each two bytes to an Int16.  It is certainly easier to maintain the code with a copy.

Any thoughts?

David

Monday, February 19, 2007 7:20 PM