Faster 16bit multiplication algorithm for 8-bit MCU

前端 未结 6 1406
没有蜡笔的小新
没有蜡笔的小新 2021-02-12 11:27

I\'m searching for an algorithm to multiply two integer numbers that is better than the one below. Do you have a good idea about that? (The MCU - AT Tiny 84/85 or similar - wher

6条回答
  •  日久生厌
    2021-02-12 11:56

    The compiler might be able to produce shorter code by using the ternary operator to choose whether to add 'a' to your accumulator, depends upon cost of test and branch, and how your compiler generates code.

    Swap the arguments to reduce the loop count.

    uint16_t umul16_(uint16_t op1, uint16_t op2)
    {
        uint16_t accum=0;
        uint16_t a, b;
        a=op1; b=op2;
        if( op1>=1;
            a+=a;
        }
    
        return accum;
    }
    

    Many years ago, I wrote "forth", which promoted a compute rather than branch approach, and that suggests picking which value to use,

    You can use an array to avoid the test completely, which your compiler can likely use to generate as a load from offset. Define an array containing two values, 0 and a, and update the value for a at the end of the loop,

    uint16_t umul16_(uint16_t op1, uint16_t op2)
    {
        uint16_t accum=0;
        uint16_t pick[2];
        uint16_t a, b;
        a=op1; b=op2;
        if( op1>=1;
            pick[1] += pick[1]; //(a+=a);
        }
    
        return accum;
    }
    

    Yeah, evil. But I don't normally write code like that.

    Edit - revised to add swap to loop on smaller of op1 or op2 (fewer passes). That would eliminate the usefulness of testing for an argument =0.

提交回复
热议问题