# two's complement encoding

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
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

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!

-

For four bits of two's complement, the range you can express is $[-8,7]$, so $C_{16}$ is out of range. The table of 4-bit two's complement in the article shows this. If you use five bits, $C_{16}=01100_2$ just fine and is positive.

-

Just a tangential remark: while the algorithm given in the Wikipedia article does work, even if it seems kind of confusingly written, I personally find this version simpler:

1. Write down (the absolute value of) the number in binary.