Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer

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.
  2. Add leading zeros to get the desired number of bits.
  3. If the original number was negative, invert all the bits and add one to the result.

This way, by doing the padding before the inversion, you don't need to keep track of how many leading zeros your intermediate results have.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.