1

How does two's complement work? For example:

5: 00000101 -5 (two's complement): 11111011 

How can one tell if the latter is supposed to be 251 or -5?

4 Answers 4

4

They are both and none. 11111011 is just a bit pattern - it only aquires some inherent sense, if used in some operation, such as arithmetic.

Depending which operation you use, the interpretation may differ or not - the reason why 2's complement is used, is that e.g. in integer arithmetic the bit-pattern result of the operation will be correct, no matter if you interpret it as signed or unsigned.

Sign up to request clarification or add additional context in comments.

Comments

2

If its a signed integer, the most significant bit of it, works as its sign bit. If the sign bit is 0 the number is positive. If the sign bit is 1 the number is negative and is presented in 2's complement form and the compiler does 2's complement operation to handle these negative integers.

But in the case of unsigned integer declared explicitly as "unsigned int", there is no sign bit and no 2's complement interpretation.

So for signed 8 bin int 11111011 is the 2's complement of 5, hence represents -5, but for unsigned 8 bit int 11111011 is 251 as you mentioned.

1 Comment

I guess technically the statement "So for signed 8 bin int 11111011 is the 2's complement of 5" is wrong, it should be rephrased as "So for signed 8 bit int 11111011 is the 2's complement which when converted would be -5, where MSB is 1 which indicates the number stored is negative and for the rest all bit when we do it's 2's compliment we get 5"
2

You can't! This is the reason that many languages have signed and unsigned types. It's so the compiler/interpreter knows whether to interpret a binary value as signed (two's complement) or unsigned.

Comments

1

To better understand Two's complement have a look at the Wikipedia page

The interpretation of the strings of bits depend on the instructions who are going to use that data. If you declare a variable as unsigned that bits are interpreted as a regular binary number. Otherwise, if you declare it as a signed variables it is interpreted as a two's complement value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.