Reputation: 73
How can I mupltiply a natural number with a constant (also natural)?
I am fairly new to PIC and assembler and I need just a simple example to understand how it works (say multiplying 5 and 6 or 5 and 3). I am doing some homework and I am only multiplying small number for now so I don't need examples for bigger numbers and how to handle overflowing and similar.
I found online that this can be done in the following example but it doen't seem right to me so I guess I just don't understand it.
movlw d'5'
; multiply W register by 6
addwf W, F
addwf W, F
addwf W, F
I would appreciate any help.
Upvotes: 0
Views: 588
Reputation: 1688
I'm not familiar with your assembly language, but in general if you want to multiply by a constant it's easiest to think about the problem in terms of factors of powers of 2.
(Forgive me, I don't know the HTML code for math textbook script)
Let's say you want to multiply a number by 320. Something that you'll do commonly for retro hardware with a 320-pixel wide screen.
We can take 320 * x
and factor it into a sum of powers of two (here's a hint: it helps to look at the binary representation of the number you wish to multiply by!)
320x = 256x + 64x
While this seems like a more complicated problem for a computer to solve, it's actually not, since most CPU architectures have a "bit shift" operation, which is effectively a very fast "multiply-by-two." Even for computers that do have a hardware mul
operator, the compiler will prefer to write the multiplication in terms of bit-shifts and adds simply to save time. Despite the code taking up more bytes in your program, it's much quicker than an actual mul
.
If you don't have a dedicated bit shift instruction, simply adding a register to itself will have the same outcome. In the example above you'd need to copy the starting value to another register first, then do the multiplications separately and add them together at the end.
For a simpler example, if you just want to multiply by 10:
; 10x = 8x + 2x
You can copy your starting value to another register (if you have any) or memory (if you don't.) Then add that value to itself 3 times. Then take the value you backed up earlier, and add it to itself once. Finally, add the two together and you get your result.
Upvotes: 2