Converting negative decimal to binary
Solution 1:
You're confused because you forgot that there must be something that distinguishes positive numbers from negative ones.
Let's say you want to store non-negative numbers on 8 bits.
-
00000000
is 0, -
00000001
is 1, -
00000010
is 2, -
00000011
is 3, -
00000100
is 4, - ...
-
11111111
is 255
So you can store numbers in range 0-255 on 8 bits. 255 = 28 - 1. (2 is the base of binary system, 8 is the number of bits, 1 is subtracted because we want to count 0 in)
Now, let's say you want to store negative numbers too. How can we achieve that? We can dedicate one bit for sign. If this bit is 0
then we interpret other 7 bits as a positive number, otherwise as a negative number. It's best to use most significant bit for sign because it makes some operations easier.
-
Trivial approach: Just read a number as-is:
-
00000001
== 1 and10000001
== -1 -
01000010
== 66 and11000010
== -66 -
01111111
== 127 and11111111
== -127
-
-
Ones' complement: For any number
x
, negating its binary representation yields binary representation of-x
. This means that:-
00000001
== 1 and11111110
== -1 -
01000010
== 66 and10111101
== -66 -
01111111
== 127 and10000000
== -127
-
-
Two's complement: For any number
x
, negating its binary representation and adding 1 yields binary representation of-x
. This means that:-
00000001
== 1 and11111111
== -1 -
01000010
== 66 and10111110
== -66 -
01111111
== 127 and1000001
== -127 -
10000000
== -128
-
Why is two's complement the best?
- Because it has the widest range: -128...127, while trivial approach and ones' complement have -127...127
- Zero is well defined:
- In two's complement only
00000000
is zero - In trivial approach both
00000000
and10000000
are zero - In ones' complement both
00000000
and11111111
are zero
- In two's complement only
- Addition and subtraction is identical as with unsigned numbers, so CPU doesn't need additional instructions for adding signed numbers.
Note that if we dedicate most significant bit for sign bit, then we can't convert number to binary without knowing how many bits we will need. For example is we have 4 bits, then the number -5 in trivial approach is 1101
, on 7 bits it would be 1000101
. 0001101
(4-bit -5 padded with zeros to 7 bits length) is actually 13 (most significant bit is 0, so it's positive).
I won't do the homework for you, but I can give you general tips:
To convert -x
to N
bits long two's complement representation:
- Convert
-x
to binary using two's complement. - Left-pad it with zeros up to
N-1
length. - Add the negative sign bit on the left side.
I think you can figure out the rest from this answer. If you have any more questions, leave a comment.