# [sdiy] I suck at halfband filters and maths...

Matthias Puech matthias.puech at gmail.com
Mon May 28 22:28:38 CEST 2018

```How about using a CIC filter then?

They are basically moving average filters with decimation built-in. They
don't need multiplication at all, and I love how they work by design with
modular arithmetic (wraparound is a feature, not a bug).

Here's a C++ implementation that works (optimized with templates):

<<<<
constexpr int ipow(int a, int b) {
return b==0 ? 1 : a * ipow(a, b-1);
}

// N number of stages, R decimation rate
// careful: gain must be <= 2^16
template<int N, int R>
class CicDecimator {
int32_t hi[N] = {0};
int32_t hc[N] = {0};
static constexpr int gain = ipow(R, N);
public:
// reads [R*size] input samples, writes [size] output samples:
void Process(int16_t *input, int16_t *output, size_t size) {
while(size--) {
// N integrators
for (int i=0; i<R; i++) {
hi[0] += *input++;
for(int n=1; n<N; n++) {
hi[n] += hi[n-1];
}
}
// N combs
int32_t v = hi[N-1];
for (int n=0; n<N; n++) {
int32_t in = v;
v -= hc[n];
hc[n] = in;
}
*output++ = static_cast<int16_t>(v / gain);
}
}
};
>>>>

On Sun, May 27, 2018 at 12:20 AM Gordonjcp <gordonjcp at gjcp.net> wrote:

> On Thu, May 17, 2018 at 03:45:51PM +0100, rburnett at richieburnett.co.uk
> wrote:
> > Is this just a thought exercise or is it required for a particular
> > application?
> >
> > This isn't how *I* personally would make a half-band filter.  They
> > are usually done with FIR filters if the ultimate aim of the game is
> > to drop the sample rate down (decimation.)
> >
> > FIR has a number of advantages here over IIR here:  It is inherently
> > stable (even with coefficient rounding on your low-end micro,) it
> > has linear phase response, and you don't need to calculate the
> > output samples that you will be throwing away later in the
> > decimating process.
>
> Right, but for FIR you'd need a multiplier and a whole bunch of
> registers for the taps, which I'm keen to avoid.
>
> --
> Gordonjcp
>
> _______________________________________________
> Synth-diy mailing list
> Synth-diy at synth-diy.org
> http://synth-diy.org/mailman/listinfo/synth-diy
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://synth-diy.org/pipermail/synth-diy/attachments/20180528/94e493a4/attachment.html>
```