1.4.4.15 Fract_log2fix Function

int32_t Fract_log2fix (int32_t X32, size_t precision)

Summary

Calculates fixed point base 2 logarithm using number of fractional bits specified by precision argument.

Description

Calculates fixed point base 2 logarithm using number of fractional bits specified by precision argument. This implementation is based on Clay. S. Turners fast binary logarithm algorithm.

Preconditions

None.

Parameters

X32 Fixed point input, if x == 0, function returns INT32_MIN to represent negative.

infinity. If x < 0 function returns INT32_MAX as error.

precision number of fractional bits in input and output, 1<= precision <= 31.

if precision < 1 or precision > 31 function returns INT32_MAX as error.

Returns

Logarithm base 2 of input, in same Q format as input. The Q format used is based on the value of precision. For example, if precision == 16 then the Q format used is Q15.16.

Remarks

If precision = N, then the input and output are Q(31-N).N.

For example, if precision = 16 then the input and output are Q15.16.

This means that there are 16 fractional bits (the LS word) and the upper 16 bits (MS word) represents an int16_t integer.

References: C. S. Turner, "A Fast Binary Logarithm Algorithm", IEEE Signal Processing Mag., pp. 124,140, Sep. 2010.

Example

_// Make log output Q15.16_

#define PRECISION 16

#define STRING_MAX_SIZE 133

char ioString[STRING_MAX_SIZE];

double Xdouble;

double scale = 1U &lt;&lt; PRECISION;

float Xfloat;

int16_t X16;

int32_t X32;

while ( Xdouble != -1.0 )

{

sprintf(ioString,&quot;rnX: &quot;);

SendDataBuffer(ioString, strlen(ioString) );

GetDataBuffer(ioString,STRING_MAX_SIZE);

sscanf(ioString,&quot;%f&quot;,&amp;Xfloat);

Xdouble = Xfloat;

if ( Xdouble == -1 )

{

sprintf(ioString,&quot;rnWe&#39;re done!rn&quot;);

SendDataBuffer(ioString, strlen(ioString) );

return 0;

}

else if ( Xdouble &lt; 0 )

{

sprintf(ioString,&quot;%f is Negative!rn&quot;,Xdouble);

SendDataBuffer(ioString, strlen(ioString) );

continue ;

}

else if ( Xdouble &gt;= 1 &lt;&lt; (32 - PRECISION) )

{

sprintf(ioString, &quot;%f is too bigrn&quot;, Xdouble);

SendDataBuffer(ioString, strlen(ioString) );

continue ;

}

sprintf(ioString,&quot; log10(%f) = %frn&quot;, Xdouble, ( double )log10(Xdouble));

SendDataBuffer(ioString, strlen(ioString) );

X32 = Fract_log10fix(Xdouble * scale, PRECISION);

sprintf(ioString,&quot;Fract_log10fix(%f) = %f (0x%08X)rn&quot;, Xdouble, X32/scale, X32);

SendDataBuffer(ioString, strlen(ioString) );

X32 = Fract_log2fix(Xdouble * scale, PRECISION) ;

sprintf(ioString,&quot; Fract_log2fix(%f) = %f (0x%08X)rn&quot;, Xdouble, X32/scale, X32 );

SendDataBuffer(ioString, strlen(ioString) );

}_//end while ( Xdouble != -1.0 )_

C

int32_t Fract_log2fix (int32_t X32 , size_t precision );