0

Ok, so here's the problem: 11100111 - 110011111

I am aware of the fact that we have to use 2's complement method for gaining the right answer but when I do use it by changing 110011111 to 001100000 and then add it to 11100111, I get (1)01001000. However, the answer to this problem is -10111000 [yes, that's a negative].

I am really very confused as to how we can possibly get a negative result using the 2's complement method for the above problem. I searched stack overflow but no post seemed to answer this query of mine. Thanks, in advance for helping me out!

Kaya
  • 1
  • 1
  • Are you trying to do this with code? Or doing it by hand? Your second parameter is 9 bits long, so that must be at least a short. Your taking 231 and subtracting 415 which must give you -184, no? – Scratte Jul 13 '21 at 02:33
  • Note that `byte a = (byte) 0b11100111;` is negative, while `short a = 0b11100111;` is positive. Note that only the most significant bit on the datatype matters, so `110011111` isn't a negative. It's implied that `0b110011111` really is `0b0000000110011111`. – Scratte Jul 13 '21 at 02:47

1 Answers1

0

Any binary number with the first bit being 1 is negative if its a signed number, so since you have (1)0111000 it is a negative value. It seems you are confusing signed and unsigned numbers.

You are also incorrectly doing two's compliment, you should first subtract the binary number from the other normally then add 1 to it. This is an example from wikipedia

   1111 1111                       255.
 − 0101 1111                     −  95.
  ===========                     =====
   1010 0000  (ones' complement)   160.
 +         1                     +   1
  ===========                     =====
   1010 0001  (two's complement)   161.
Sean Powell
  • 564
  • 4
  • 20