Fast way to convert float range from -1 to 1 to short?

I need to repeatedly convert 1024 + consecutive 4 byte floats (range from -1 to 1) into 2 byte shorts (range from -32768 to 32767) and write to disk.

I am currently doing this with a loop:

short v = 0;
for (unsigned int sample = 0; sample < length; sample++) 
{
    v = (short)(inbuffer[sample * 2] * 32767.0f);
    fwrite(&v, 2, 1, file);
}

And it works, but floating point computation and the road loop. Can this be optimized?

+3
source share
4 answers
short v = 0;
for (unsigned int sample = 0; sample < length; sample++) 
{
    v = (short)(inbuffer[sample * 2] * 32767.0f);
    // The problem is not here-------^^^^^^^^^^^
    fwrite(&v, 2, 1, file);        
    // it is here ^^^^^^^
}

Mac (objective-c, iphone ?) . fwrite, , , , , , . :

short v[SZ] = 0;
// make sure SZ is always > length, or allocate a working buffer on the heap.
for (unsigned int sample = 0; sample < length; sample++) 
{
    v[sample] = (short)(inbuffer[sample * 2] * 32767.0f);
}
fwrite(v,sizeof(v),1,file);
+6

, fwrite . :

short outbuffer[length]; // note: you'll have to malloc this if length isn't constant and you're not using a version of C that supports dynamic arrays.
for (unsigned int sample = 0; sample < length; sample++) 
{
    outbuffer[sample] = (short)(inbuffer[sample * 2] * 32767.0f);
}
fwrite(outbuffer, sizeof *outbuffer, length, file);
+2

, , -

short v = 0;
short outbuffer = // create outbuffer of required size
for (unsigned int sample = 0; sample < length; sample++) 
{
    outbuffer[sample] = (short)(inbuffer[sample * 2] * 32767.0f);
}

fwrite(outbuffer, 2, sizeof(outbuffer), file);
+2

- :

out[i] = table[((uint32_t *)in)[i]>>16];

table - , 16 IEEE int16_t, . . 23 (1 , 8 14 ) , , 16 , , .

Are you sure floating point conversions are slow? As long as you use fwritethis way, you spend 50-100 times more CPU time in fwritethan with floating point arithmetic. If you are dealing with this problem and the code is still too slow, you can use the approach of adding magic offsets and reading the mantissa bits to convert to int16_tinstead of multiplying by 32767.0. It may or may not be faster.

0
source

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


All Articles