简体   繁体   中英

Fastest way to convert float to bytes and then save byte array in memory?

I am currently writing code that converts an audio clip into a float array and then want to convert that float array into bytes, and finally convert that byte array to hexadecimal.

Everything works but we are attempting to save arrays of data that are hundreds of thousands of elements long when this data is converted to bytes and once we try to save this data as a hexadecimal string it is a bit much or takes too long for the mobile devices we are testing on to handle.

So my question is are there any ways to optimize / speed up this process?

Here is my code for Convert our float array to bytes:

public byte[]  ConvertFloatsToBytes(float[] audioData){

    byte[] bytes = new byte[audioData.Length * 4];

        //*** This function converts our current float array elements  to the same exact place in byte data 
        Buffer.BlockCopy(audioData,0,bytes,0,bytes.Length);



    return bytes;
}

Here we convert that data into a hex string :

public static string ByteArrayToString(byte[] ba)
    {
        string hex = BitConverter.ToString(ba);

        //Debug.Log("ba.length = " + ba.Length.ToString() +"hex string = " + hex);
        return hex.Replace("-","");
    }

Ultimately at the end we save the string out and convert it from the hex string to a float array .

Like I said that code is slow but it is working I am just trying to find the best ways to optimize / speed up this process to improve performance

Do you know which part is costing you? I strongly suspect that the conversion to a hexadecimal array isn't the bottleneck in your program.

The final part, where you remove the hyphens ends up copying the string. You can probably do better by writing your own method that duplicates what BitArray.ToString does, without the hyphens. That is:

const string chars = "0123456789ABCDEF";

public string ByteArrayToString(byte[] ba)
{
    var sb = new StringBuilder(ba.Length*2);
    for (int i = 0; i < ba.Length; ++i)
    {
        var b = ba[i];
        sb.Append(chars[b >> 4]);
        sb.Append(chars[b & 0x0F]);
    }
    return sb.ToString();
}

That will avoid one string copy.

If you're willing to use unsafe code (don't know if you can on the devices you're working with), you can speed that even further by not even copying to the array of bytes. Rather, you fix the array of floats in memory and then address it with a byte pointer See Unsafe Code and Pointers if you're interested in that.

That sounds really convoluted - are audio samples not normally integers?

Anyway, StreamWriter supports writing of single and double natively, so you could use that to build a memory stream that you then convert to hex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM