Search code examples
assemblyx86-16multiplicationtwos-complement

How to multiply by -1 without using `MUL` or `NEG`


I got an assignment to write a program in assembly that can multiply a number by -1 without using the neg or mul instructions. I tried to use shl and shr but I can't make it work for some reason. Does someone know how I can do it? (in the binary signed 2's complement)

This is the frame of the code:

org 100h

jmp start


start:
  mov bx, 0000000000000010b
  ; here i need to multiply by -1 the number that in bx
mov ah, 0
int 16h
ret

Solution

  • A way to multiply by -1 could be to flip all the bits and then add 1. i.e. let's take seven in 4 bits (I use 4 bits for the sake of the example).

           7(10) = 0111(2)
    Flip the bits: 1000
    and add 1:     1001
    

    As you can see we have -7. To do this in assembly you could use not.

    In this way the zeroes become ones and the ones become zeroes, after the flip you simply add 1 and you should have it.
    The shl and shr can be seen as multiplying or dividing by 2**numberOfBitShifted, that's why they can't work.