views:

437

answers:

3

I've got a byte() array returned as result of directx sound capture, but for other parts of my program I want to treat the results as single(). Is trundling down the array item by item the fastest way of doing it or is there a clever way to do it ?

The code that gets it is

CType(Me._applicationBuffer.Read(Me._nextCaptureOffset, GetType(Byte), LockFlag.None, LockSize), Byte())

which creates the byte array, can Ctype handle single ? (note, I can't figure out a way to do it!)

A: 

Try

float f = BitConverter.ToSingle(bytearray, 0);

In VB (I think):

Dim single s;
s = BitConverter.ToSingle(bytearray, 0);
MusiGenesis
That's not what he's asking.Also, VB doesn't use a semicolon! I make that mistake whenever I'm forced to touch VB ;-)
Vincent McNabb
A: 

Sorry, no. x=BitConverter.ToSingle(bytearray,0) returns a single element of type single, not an array of single. (value x = -1.58998939E+35 {Single}, if that helps!)

WaveyDavey
For future reference this should have been added as a comment to MusiGenesis' post.
Bryan Anderson
I see MusiGenesis has two posts, I was refering to the BitConverter version.
Bryan Anderson
+1  A: 
public float[] ByteArrayToFloatArray(byte[] byteArray)
{
    float[] floatArray = new float[byteArray.Length / 4];
    for (int i = 0; i < floatArray.Length; i++)
    {
        floatArray[i] = BitConverter.ToSingle(byteArray, i * 4);
    }
    return floatArray;
}

The fastest way to do this (in terms of performance as opposed to how long it takes to write) would probably be to use the CopyMemory API call.

MusiGenesis
might need to add a check to make sure bytearray.Length % 4 == 0 ?
Mitch Wheat
His byte array is from audio data, so the length will probably often not be a multiple of 4.
MusiGenesis
Fixed it. Thanks Mitch.
MusiGenesis
It just occurred to me that if his data is stereo, then it will probably always be a multiple of 4.
MusiGenesis