Primitive Math

In a recent Lesson, I explored upon the idea of creating binary math macros. This technique was popular in Assembly language programs where the processor lacks high order math functions, including basic multiplication and division. In C you can code one-line macros that mimic Assembly’s bit-shifting behavior required to multiply values.

For example, to multiple a value by three, the following macro is used:

#define BYTHREE(a) a+(a<<1)

The value of variable a is added to itself shifted left one spot, which is essentially a+(a*2), or 3*a.

For this month’s Exercise, you are to write 11 such macros, each corresponding to a multiplication value:

BYONE(a)
BYTWO(a)
BYTHREE(a)
BYFOUR(a)
BYFIVE(a)
BYSIX(a)
BYSEVEN(a)
BYEIGHT(a)
BYNINE(a)
BYTEN(a)

These macros are used to manipulate the value 6, as shown by this code skeleton:

#include <stdio.h>

/* Macros go here */

int main()
{
    printf("%d *  1 = %d\n",6,BYONE(6));
    printf("%d *  2 = %d\n",6,BYTWO(6));
    printf("%d *  3 = %d\n",6,BYTHREE(6));
    printf("%d *  4 = %d\n",6,BYFOUR(6));
    printf("%d *  5 = %d\n",6,BYFIVE(6));
    printf("%d *  6 = %d\n",6,BYSIX(6));
    printf("%d *  7 = %d\n",6,BYSEVEN(6));
    printf("%d *  8 = %d\n",6,BYEIGHT(6));
    printf("%d *  9 = %d\n",6,BYNINE(6));
    printf("%d * 10 = %d\n",6,BYTEN(6));

    return(0);
}

Here’s sample output, assuming the macros are created and added to the above skeleton:

6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
6 * 10 = 60

The macros can be coded in a number of ways, though you are restricted to using the + and << shift operators. And while you can just use addition, as in a+a+a for BYTHREE(), don’t. See how clever you can be with the left-shift operator to keep the macros as tight as possible. Further, don’t try to use the definition of one macro within another.

Please try this Exercise on your own before you check my solution, which I’ll post in a week.

Leave a Reply