´
Concise and to the point. I like the way!
Hi,
Well thanks, and you made me realize that i probably should have also mentioned that any power of 2 can be done that way too, such as:
x*2: shift 1 time to the left
x*4: shift 2 times to the left
x*8: shift 3 times to the left
x*16: shift 4 times to the left
x*32: shift 5 times to the left
So the number of shifts to the left comes from the exponent in:
x*2^n
where n is the number of left shifts required.
The one catch is that we have to watch out how many bits our register can handle without an overflow. For example, if we have a binary number using an 8 bit register and we have first:
0101 0001
the first shift leads to:
1010 0010
but the second shift leads to:
0100 0100
which means we lost the first '1' and so the result is no good.
In this case, we detect a carry and use a second register to handle the upper bits. in this way we can handle any size argument even a 32 bit number as long as we have enough registers available. If we use a higher level language though this is probably already taken care of for us in the framework of the language.
There are other tricks too when working in asm especially. For example, if we have to multiply by 10 we dont find an exponent 'n' that works for that, we only have 8 and 16, which is not right. But we do realize that 10 can be broken down into 2*5, and 5 can be broken down into 4 and 1, which means we can shift the number three times to the left, add the original back to it, then shift the result once to the left:
say we want to multiply this times 10:
A=0000 1001
shift it to the left two times (this comes from the 4):
B=0010 0100
add that to the original (from the 1):
C=A+B=0010 1101
shift that to the left once (from the 2):
D=0101 1010
So we just took 9 and multiplied it by 10 and got 90 as result.
Another trick with the same problem would go like this...
Start with 9 again:
A=0000 1001
and we want to multiply by 10 which is 1010 in binary.
By looking at the bits in the 1010 we see two 1's, in positions 8 and 2. So to do it this other way we first shift three times:
B=0100 1000
and shift the original 1 time:
C=0001 0010
then add the two:
D=B+C=0101 1010
which again is 90.