I'm referring to this article: http://en.wikipedia.org/wiki/Two's_complement
I want to convert the following number to two's compliment using 4 bits: Decimal: -6, 6, 1 hexadecimal: C,D,E In the article it says:
Algorithmically, to create a two's complement binary value: 1. express the binary value for the positive number 2. if the original value was negative, 2a. complement the value 2b. add one 3a. if the value is positive, add leading zeros to achieve the proper number of bits 3b. if the value is negative, add leading ones to achieve the proper number of bits (3. replicate the MSB to achieve the proper number of bits)
So, What I'm doing:
6 -> converting to binary -> 110 -> adding leading zeros to make 4 bytes -> 0110
-6 ->Converting positive to binary -> 110 -> inverting bytes ->001 -> adding 1 -> 010 -> adding leading 1's -> 1010
1-> converting -> 1 -> adding leading zeros -> 0001
Looks good so far. (Maybe not...) Here's when I'm experiencing a trouble. I need to convert hex value to two's compliment. for example C.
here's what I do:
c-> convert to dec -> 12 -> convert to binary -> 1100
Which is not quite right, because later in the article they say that:
The most significant bit is 1, so the value represented is negative.
AND
The most significant bit is 0, so the pattern represents a non-negative (positive) value.
So if looking at value 1100 we see that it has first bit is 1, so the value should be negative, but 12 is positive.
I'm a little confused here. let me know what I'm doing wrong.
Thanks!