Multiplying Without Multiplication

Long, long ago, I was an ardent assembly language programmer. I admired coding in assembly because the programs were small and fast. On the early microcomputers, that was a plus.

The problem with assembly is that it takes a heinously long time to produce a workable program. That’s because you pretty much have to code everything yourself, including math functions.

For example, when I coded in Z80 and then 8086, a multiplication operator didn’t exist. When you wanted to multiply two numbers, you had to concoct a method on your own, either by adding values or by using a bit-shift operation, which doubled values. That’s the inspiration behind this week’s code:

#include <stdio.h>

int main()
{
    int value,two,eight,ten;

    printf("Enter an integer value: ");
    scanf("%d",&value);

    two = value << 1;
    eight = value << 3;
    ten = two + eight;

    printf("Ten times %d is %d.\n",value,ten);

    return(0);
}

Before explaining the code, copy and paste it into your editor. Build and run to ensure that it works. Here’s some sample output:

Enter an integer value: 14
Ten times 14 is 140.

It would have been really easy to include the line value*=10 in the code, which would have multiplied the original input by ten. But that doesn’t explain how us ancient Assembly coders did things.

The key to the program’s success at multiplication is the << operator, which appears at Lines 10 and 11. That’s the bit-wise shift operator. Its effect on integer values is to multiply by a power of two. That’s what happens when the bits in an integer are shifted to the left. (Shifting to the right with >> divides an integer by a power of two.)

So the operation at Line 10 shifts the bits in value one position to the left. The value is effectively doubled and the result sotred in the two variable.

The operation at Line 11 shifts the bits in value three positions to the left, which is the same as multiplying value by 23, or 8. Coincidentally, that value is stored in the eight variable.

Line 12 performs the “multiplication” by adding the value from variable two plus the value of variable eight. The end result, two + eight, equals ten times the original value. That’s the way I did things in Assembly language back in the day.

These operations work for values up to almost the full size of a signed int, which is 2,147,483,647 on most systems. So if you specified the value 3000000000 in the program, the result gets hinkey. (You’d have to type the value variable as a long or long long to handle such huge values.)

Oh, and this code does not compile properly under C++. That’s because in C++ the << operator is used for stream input.

Leave a Reply