Saturday, February 7, 2009

Commonly used C code DSP applications

Finding Endianess:

enum byte_order { unknown, bigEndian, littleEndian };

static enum byte_order determine_endianess (void)
{
char s[sizeof (long) + 1];
union {
long longval;
char charval[sizeof (long)];
} probe;
probe.longval = 0x41424344L; /* ABCD in ASCII */
strncpy (s, probe.charval, sizeof (long));
s[sizeof (long)] = '\0';
/* fprintf( stderr, "byte order is %s\n", s ); */
if (strcmp (s, "ABCD") == 0)
return bigEndian;
else if (strcmp (s, "DCBA") == 0)
return littleEndian;
else
return unknown;
}

Endianess conversion
: Big Endian to Little Endian

C code:

#define BE2LE_32(_x) \
((_x) <<>> 8 & 0x0000FF00 \
| (_x) >> 24 & 0x000000FF)

#define BE2LE_16(_x) ((_x) <<>> 8 & 0x00FF)

Saturation

#define SATURATE(x, max, min) \
( ((x) > (max)) ? (max) : ((x) < (min)) ? (min) : (x) ) #define TRUNCATE(x, Y, Z, DATA_SIZE) \ (((((x) >> ((Y##_##F) - (Z##_##F)))) << ((DATA_SIZE) - (Z##_##W) - (Z##_##F))) >> ((DATA_SIZE) - (Z##_##W) - (Z##_##F)))
/* <--Frac part trunc--->*/
/* <---------------------Truncating the MSB---------------------------------->*/
/* <----------------------------------Sign Extending to do the arithmetic operations in C------------------------------> */

#define RND_OFF(x, Y, Z) \
( ((x) + (1 << (((Y##_##F) - (Z##_##F)) - 1))) >> ((Y##_##F) - (Z##_##F)) )

USAGE:
definition Q1:
#define Q_FMT1_W 3 // whole part
#define Q_FMT1_F 14 // fractional part

definition Q2:
#define Q_FMT2_W 3 // whole part
#define Q_FMT2_F 7 // fractional part

Rounding off:
RND_OFF(val, Q_FMT1, Q_FMT2);

Saturate:
SATURATE(val, 255, -256);

Truncate:
TRUNCATE(val, Q_FMT1, Q_FMT2, 31);

No comments:

Post a Comment