Question

I have been analyzing a code and trying to understanding each part of the algorithm. I came across this part where the bitwise and operator was used

if (qpd >= 0) qpd += qpd&1;
else qpd -= qpd&1;

From what I understand, the algorithm wants to use the 1 as a mask for the variable qpd but since the number is just 1, there's not much sense in doing an operation that virtually does not make any changes. Please enlighten me here since I'm lost.

The foor loop, which gets the magnitude and frequency of the data from an array, that uses the bitwise operator is as follows:

/* this is the analysis step */
            for (k = 0; k <= fftFrameSize2; k++) {

                /* de-interlace FFT buffer */
                real = gFFTworksp[2*k];
                imag = gFFTworksp[2*k+1];

                /* compute magnitude and phase */
                magn = 2.*sqrt(real*real + imag*imag);
                phase = atan2(imag,real);

                /* compute phase difference */
                tmp = phase - gLastPhase[k];
                gLastPhase[k] = phase;

                /* subtract expected phase difference */
                tmp -= (double)k*expct;

                /* map delta phase into +/- Pi interval */
                qpd = tmp/M_PI;
                if (qpd >= 0) qpd += qpd&1;
                else qpd -= qpd&1;
                tmp -= M_PI*(double)qpd;

                /* get deviation from bin frequency from the +/- Pi interval */
                tmp = osamp*tmp/(2.*M_PI);

                /* compute the k-th partials' true frequency */
                tmp = (double)k*freqPerBin + tmp*freqPerBin;

                /* store magnitude and true frequency in analysis arrays */
                gAnaMagn[k] = magn;
                gAnaFreq[k] = tmp;

            }
Was it helpful?

Solution

The code is used to round numbers to next even value; rounding positive numbers up and negative numbers down: for example

7 becomes 8
12 remains 12
-7 becomes -8

it works by adding or subtracting the last bit of the value that is 1 for odd numbers or 0 for even numbers.

OTHER TIPS

Well I'm not entirely sure what all that is doing as a whole but all the & operator is doing is basically either adding one or zero, if the qbd is above or equal to zero, or subtracting one or zero (all based on what the first bit is) if it is less than zero.

Not sure if that's what you're looking for.

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