Mark
Mark

Reputation: 15

How to divide in assembly language using addition?

In a computer engineering class in high-school, we were given an assignment where we have to divide 2 numbers in assembly language by using the process of addition.

The toy architecture we're programming for doesn't have a division instruction. The machine has 2's complement addition and bitwise AND/OR/XOR operations, but not subtraction directly: https://www.csie.ntu.edu.tw/~r03944025/intro2015/files/hw/appendix_c

(Editor's note, the textbook doesn't define a text assembly language, only machine code opcodes and operands for this load/store machine with sixteen 8-bit registers, and a conditional jump-if-zero instruction.)

Upvotes: 0

Views: 3064

Answers (1)

Martin Rosenau
Martin Rosenau

Reputation: 18503

Because I don't want to do your school homework, I will only give you some hints:

How to divide ... using addition?

It is not the fasted method, but you can do the following:

; Calculate C = A / B
Set C to 0
As long as A >= B:
    Increment C by 1
    Subtract B from A

If A and B may be negative, do the following:

Set D to 0
If A is negative:
    Set D to 1
    Negate A
If B is negative:
    Xor D with 1
    Negate B
Perform C = A / B (see above)
If D != 0:
    Negate C

The toy architecture ... has 2's complement addition and bitwise AND/OR/XOR operations ...

... and a conditional jump instruction that jumps if two registers are equal as well as a rotate operation.

This is very important because with bitwise operations and addition only, bit 0 of the result of some operation would only depend on bit 0 of the operands. This means that bit 0 of the final output of some program would only depend on bit 0 of the inputs.

However, for the two divisions 0x30 / 0x10 = 3 and 0x20 / 0x10 = 2 bit 0 of all inputs is 0, but in one case bit 0 of the output is 1 and in the other case bit 0 of the output is 0.

but not subtraction directly

Some hints about some operations your CPU does not have:

  • Inverting all bits of a number can be done with a XOR operation.
  • Please recall how to negate a number in two's complement.
  • If you are able to negate a number and to add numbers, you should also be able to subtract numbers.
  • Please recall how to find out if a two's complement's number is negative.
  • If you operate with numbers in the range 0...127 only, checking for "A<B" can be done by checking for "(A-B) is negative".
    Note that this is the case when you allow negative inputs!
  • If you are operating with the whole range 0...255, checking for "A<B" is more difficult:
    • If bit 7 is "1" in A but "0" in B, then A<B is false
    • If bit 7 is "0" in A but "1" in B, then A<B is true
    • If bit 7 has the same value in A and B (either both bits are "0" or both bits are "1"), the check for "(A-B) is negative" can be done

Upvotes: 2

Related Questions