Re: scaling coefficients for c



sonos wrote:

I understand the requirement of scaling coefficients for fixed point
microcontrollers. However, I cannot seem to get past a simple issue... How
do I code a fraction in binary form for use in c code or asm language?

for example, consider the fraction in base 10: dec == 0.58642
and the same fraction in binary
bin == 0.1001011
and the same fraction in hex
0.961F9F01C

but how do I set a c variable in binary form for fractions?

I have two general rules:
1. Make your program human readable.
2. Make the compiler do the work.

I would define a type, scale factor, and conversion macro for the scaled values:

typedef unsigned short tVmeas; /* input voltage * VMEAS_SCALE/volt */
#define VMEAS_SCALE 4096 /* tVmeas scale factor */
#define VOLTS_TO_VMEAS(v) ((tVmeas)((v)*VMEAS_SCALE+0.5))
....
tVmeas vin = VOLTS_TO_VMEAS(0.58642); /* input voltage, with default value */

The scale factor is defined in one place (it need not be a power of 2). There is a specific type, tVmeas, that is commented to show the units of any associated variable. The macro VOLTS_TO_TVMEAS, if used with a constant expression, is normally evaluated at compile time so that there is no floating point arithmetic in the generated code. Compile time conversion is not guaranteed, but works for all the compilers that I have used, including many targeting 8-bit processors.

--
Thad
.



Relevant Pages

  • Re: scaling coefficients for c
    ... I understand the requirement of scaling coefficients for fixed point ... do I code a fraction in binary form for use in c code or asm language? ... a real number x has a fixed-point representation xhat ...
    (comp.dsp)
  • Re: scaling coefficients for c
    ... I understand the requirement of scaling coefficients for fixed point ... How do I code a fraction in binary form for use in c code or asm ... a real number x has a fixed-point representation xhat ...
    (comp.dsp)
  • Re: scaling coefficients for c
    ... I understand the requirement of scaling coefficients for fixed point ... How do I code a fraction in binary form for use in c code or asm ... a real number x has a fixed-point representation xhat ...
    (comp.dsp)
  • Re: scaling coefficients for c
    ... I understand the requirement of scaling coefficients for fixed point ... microcontrollers. ... do I code a fraction in binary form for use in c code or asm language? ...
    (comp.lang.c)
  • Re: scaling coefficients for c
    ... I understand the requirement of scaling coefficients for fixed point ... microcontrollers. ... do I code a fraction in binary form for use in c code or asm language? ...
    (comp.lang.c)