How to cast binary resource to short array?
I need to process a binary resource (contents of a binary file). The file contains shorts. I can't figure how to cast the result of accessing that resource to a short array though:
short[] indexTable = Properties.Resources.IndexTable;
doesn't work; I can only use
byte[] indexTable = Properties.Resources.IndexTable;
Using Array.Copy
wouldn't work since it would convert each byte from the array returned by accessing the resource to a short.
How do I solve this problem please (other than manually converting the byte array)? Is there a way to tell C# that the resource is of type short[]
rather than byte[]
?
I had even trie开发者_C百科d to edit the project's resx file and change the resources' data types to System.UInt16, but then I got the error message that now constructor could be found for them.
Using VS 2010 Express and .NET 4.0.
You should use BinaryReader:
using (var reader = new BinaryReader(new MemoryStream(Properties.Resources.IndexTable)))
{
var firstValue = reader.ReadInt16();
...
}
Buffer.BlockCopy()
byte[] srcTable = Properties.Resources.IndexTable;
short[] destTable = new short[srcTable.Length / 2];
Buffer.BlockCopy(srcTable, 0, destTable, 0, srcTable.Length);
Here's how if you prefer a 'Do it yourself' style (however, I personally prefer @Joel Rondeau's method)
byte[] bytes = Properties.Resources.IndexTable;
short[] shorts = new short[bytes.Length/2];
for( int i = 0; i < bytes.Length; i += 2 )
{
// the order of these depends on your endianess
// big
shorts[i/2] = (short)(( bytes[i] << 8 ) | (bytes[i+1] ));
// little
// shorts[i/2] = (short)(( bytes[i+1] << 8 ) | (bytes[i] ));
}
精彩评论