3
\$\begingroup\$

This code takes a integer x of range [0,127] as input, returns an array of four 32-bit integers, with x bits set.

I'm trying to maximize switching to make it easier to filter out the ripple in the output. Another consideration is to make it fast because this code runs on an MCU (XMOS to be exact).

Although this code works as intended, I'm not 100% confident that this is good code.

static inline unsigned int genMask(unsigned int x)
{
    unsigned int ret=0;
    ret|=(x&0x00000001)?0x80000000:0;//x 1/32
    ret|=(x&0x00000002)?0x00008000:0;//5 1/32
    ret|=(x&0x00000004)?0x00800080:0;//4 1/16
    ret|=(x&0x00000008)?0x08080808:0;//3 1/8
    ret|=(x&0x00000010)?0x22222222:0;//2 1/4
    ret|=(x&0x00000020)?0x55555555:0;//1 1/2
    return ret;
}
static inline void genPWM(unsigned int *p, unsigned int xm)
{
    unsigned int temp = genMask(xm>>1);
    p[0] = temp;
    p[1] = temp;
    p[2] = genMask(((xm>>1)&0xfffffffe)|(xm&0x00000001));
    p[3] = genMask((xm>>1)&0xfffffffe);
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Three calls nearly identical

You are currently calling gen_mask() three times with nearly identical arguments:

genMask(xm>>1);
genMask(((xm>>1)&0xfffffffe)|(xm&0x00000001));
genMask((xm>>1)&0xfffffffe);

Notice that only the 0x1 bit is different in each case. Because of this, you can first generate this one which has its 0x1 bit cleared:

genMask((xm>>1)&0xfffffffe);

and then you can compute the other ones based on what their 0x1 bit will be.

So your code would become:

static inline void genPWM(unsigned int *p, unsigned int xm)
{
    unsigned int temp1 = genMask((xm>>1) & 0xfffffffe);
    unsigned int temp2 = temp1 | ((xm & 1) ? 0x80000000 : 0);
    unsigned int temp3 = temp1 | ((xm & 2) ? 0x80000000 : 0);
    p[0] = temp3;
    p[1] = temp3;
    p[2] = temp2;
    p[3] = temp1;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.