Question

I have a 'huge' amount of data, which may vary between 50 and 100 MegaBytes. I read this data in as an array of bytes using a filestreamer.

The thing is, I want to convert all consecutive 2 bytes into an integer. The way I do this is I loop through the array of bytes with a stepsize of two, and then use BitConvert to do the conversion:

_data[i] = BitConverter.ToInt16(soundData[i : i + 2], 0) // Convert 2 bytes into an int and store at i

So each two bytes get turned into an Int16. The problem however, is that this is too slow, as for a file of about 50 megabytes this can take up 20 seconds!

Is there a generic way of doing this instantly, instead of calling this function on each 2 bytes of my data array such that it isn't that slow? Preferably in a 'safe' way, so no unsafe code.

Was it helpful?

Solution

If the array of bytes are in the correct Endian, then just allocate an Int16 array and use Buffer.Block copy (air code):

byte[] b = new byte[]{1, 2, 3, 4};
short[] s = new short[2]; // 4 bytes long
Buffer.BlockCopy(b, 0, s, 0, 4);

OTHER TIPS

Without testing, I'm not sure I have the math and "endianess" right, but the other option would be to try something like this:

// Convert 2 bytes into an int and store at i
_data[j] = (int)soundData[i] + (soundData[i + 1] << 8);

If that's also not fast enough, then you may need a different approach to the problem.

Some other ideas can be found for the question: Convert Byte Array to Integer In VB.Net

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top