This question might seem duplicate but is not. I want to know how to convert a negative number (base-10) to 32-bit number (base-2). e.g. -9 in base-10 is equivalent to 11111111111111111111111111110111 in base-2. Kindly explain me the procedure. Thanks in advance.
Suppose you have 32 bit values as in your question, to keep my text simple. This does nevertheless apply to all numbers of bits.
In the 2's complement binary representation, the addition of two 32 bit values is identical to adding them as if the bits represented a non-negative number in the usual way. It's just that some bit-patterns represent negative numbers, in fact those with a leading 1, numbers that ordinarily we expect to be from the largest half of the collection of all 32-bit numbers.
That being the case, a bit pattern of all ones, which ordinarily would be the largest possible 32-bit number,
11111111111111111111111111111111
actually represents -1. The reason is that if you were to add 1 to this, carrying would go all the way through, replacing each 1 by 0, and the last carry would fall off the end, similarly to the way a three digit counter with 999 in it, if incremented goes back to 000. The result is
00000000000000000000000000000000
which as usual represents zero. This is how -1 + 1 = 0 works in the 2's complement representation.
Now if you take a 32-bit number n, e.g.
00010111000010101100100011110010
and bitwise complement it to get ~n, i.e. replace each 1 by 0 and each 0 by 1,
11101000111101010011011100001101
and then add these to get n + ~n,
00010111000010101100100011110010
11101000111101010011011100001101 +
--------------------------------
11111111111111111111111111111111
no carrying happens and you get a bit pattern of all ones, i.e. -1 = n + ~n and so -n = ~n + 1.
This is the key fact about the 2's complement representation: -n = ~n + 1.
Now you can solve your problem very simply. You know how to convert a positive number, and this enables you to negate it.
What's -9 ?
First convert 9 to binary as usual: 1001 with a lot of leading zeros. Then complement that, and add 1, and you have -9. Here is the sequence of events.
n : 00000000000000000000000000001001
//complement
~n : 11111111111111111111111111110110
//add 1
-n : 11111111111111111111111111110111
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With