Pergunta

In a program that seems to work well I have the following declarations:

#include <stdio.h>
#include "system.h"

signed char input[4]; /* The 4 most recent input values */

char get_q7( void );
void put_q7( char );
void firFixed(signed char input[4]);

const int c0 = (0.0299 * 128 + 0.5); /* Converting from float to Q7 is multiplying by 2^n i.e. 128 = 2^7 since we use Q7 and round to the nearest integer*/
const int c1 = (0.4701 * 128 + 0.5);
const int c2 = (0.4701 * 128 + 0.5);
const int c3 = (0.0299 * 128 + 0.5);
const int half = (0.5000 * 128 + 0.5);

enum { Q7_BITS = 7 };

void firFixed(signed char input[4])
{
    int sum = c0*input[0] + c1*input[1] + c2*input[2] + c3*input[3];
    signed char output = (signed char)((sum + half) >> Q7_BITS);
    put_q7(output);
}

int main(void)
{   
    int a;
    while(1)
    {    
     for (a = 3 ; a > 0 ; a--)
    {
      input[a] = input[a-1];
    }      
     input[0]=get_q7();           
     firFixed(input);
    }
    return 0;
}

But I don't understand how it's possibl to declare a fractional number as int which is done with the constants. It's supposed to be Q7 notation but why is it done this way and how can the compiler accept an int that is a fractional number? Will it simply take the integer part of the fraction and if so why isn't a cast required?

Foi útil?

Solução

When a floating point value is converted to an integer, it's truncated. That means that all digits after the decimal point is simply removed. E.g. 12.34 becomes 12, and 12.99 also becomes 12. There is no rounding done.

That is what the + 0.5 part does in the initializations. It's simply a way to convert a floating point value to integer with rounding. For example, 0.0299 * 128 is 3.8272 which truncated would be 3. But with the + 0.5 it's 4.3272 which truncated becomes 4, which is the rounded value of 3.8272.

There may however still be problems, and you might want to read What Every Computer Scientist Should Know About Floating-Point Arithmetic to learn more.

Outras dicas

Cast required only in case of type promotion not in case of type truncation.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top