-1

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
Sep Roland
  • 33,889
  • 7
  • 43
  • 76
roee attias
  • 95
  • 1
  • 6
  • 2
    "Two's complement" is a hint. Multiplying by -1 is flipping the sign. How are negative and positive numbers represented in two's complement? Is there a way of flipping bits other than `NEG`? – Jeroen Mostert Oct 30 '21 at 12:40
  • 2
    `neg` is the same thing as `sub` from 0. There are other ways to negate as well, of course, e.g. ones based on two's complement identities. Shifts can be ruled out because they would discard information for some possible BX values, by shifting out some bits. Negation is a 1:1 mapping, with no two numbers mapping to the same number. (0 and the most-negative number (-32768) map to themselves.) – Peter Cordes Oct 30 '21 at 12:43
  • they represented by the msb but I have no clue how can I change it – roee attias Oct 30 '21 at 12:44
  • 1
    @JeroenMostert: Flipping *just* the sign **bit** isn't what you want anyway for two's complement negation. It's very different from a sign/magnitude representation, so that hint is kind of misleading. – Peter Cordes Oct 30 '21 at 12:47
  • @PeterCordes: it's incomplete, not misleading (I talked about flipping *bits*, plural) -- gotta leave something as an exercise to the reader. – Jeroen Mostert Oct 30 '21 at 13:16
  • Canonical duplicate with the answer spelled out: [2’s complement of the word in AX without using NEG instruction](https://stackoverflow.com/q/13974417) – Peter Cordes Nov 20 '22 at 07:29

1 Answers1

2

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.

Dario Petrillo
  • 980
  • 7
  • 15