How to overlay a binary resource on a short array?

I need to process a binary resource (contents of a binary file). File contains shorts. I cannot figure out how to pass the result of accessing this resource into a short array:

short[] indexTable = Properties.Resources.IndexTable;

does not work; I can only use

byte[] indexTable = Properties.Resources.IndexTable;

Usage Array.Copywill not work, since it converts every byte from the array returned by accessing the resource to a short one.

How to solve this problem (except for manual byte array conversion)? Is there a way to tell C # that the resource is of type short[]and not byte[]?

I even tried to edit the project resx file and change the resource data types to System.UInt16, but then I got an error message that can now be found for them.

Using VS 2010 Express and .NET 4.0.

+3
3

BinaryReader:

using (var reader = new BinaryReader(new MemoryStream(Properties.Resources.IndexTable)))
{
    var firstValue = reader.ReadInt16();
    ...
}
+4

Buffer.BlockCopy()

byte[] srcTable = Properties.Resources.IndexTable;
short[] destTable = new short[srcTable.Length / 2];
Buffer.BlockCopy(srcTable, 0, destTable, 0, srcTable.Length);
+4

Here's how, if you prefer the do-it-yourself style (however, I personally prefer the @Joel Rondeau 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] )); 
}
0
source

Source: https://habr.com/ru/post/1761964/


All Articles