Two's Complement Binary representation is nothing special nor difficult to understand but is an important concept for basic integer manipulation.

When working with signed integers, it is essential to understand how integers are represented. Signed integers use Two's Complement to denote the *negative* range of integers.

Negative signed integers are denoted with the most significant bit (MSB) set to 1.

The first step is to write out the integer as if it was positive. For example, *26* would be 00011010, in a 1 byte sized integer.

Base 2 of **26** is **00011010**.

Then invert all bits. In this running example, we get, 11100101.

Inverting **00011010** by *"00011010 ^ 11111111"* gives us **11100101**.

The **XOR (^)** operation should be review, see Article 36 - Programming Bits.

Finally add one, to get the Two's Complement Binary representation of the negative integer, which gives us 11100110.

Add 1 to **11100101** by *"11100101 + 00000001"* gives us **11100110**.

After converting the positive integer to its negative equivalent, it is important to verify correctness.

Take the current integer as if it were a positive integer; for example, drop the MSB bit and use the reset of the bits to denote an unsigned integer. In the previous example, 11100110 as an unsigned integer (without MSB) is 102.

Then find the integer value of the MSB, in this case it is 128. 2 to the power of 7 is 128.

Take this MSB integer value and subtract the current integer value from it. That is 128 minus 102, and we arrive the original integer, 26.

Check for yourself, that the zero integer is itself despite the conversion formula. Zero is 00000000, inverting bits gives us 11111111, and adding one gives us 00000000 (note the disgarding of the overflow bit).

What about the one integer? One is, as a positive integer, 00000001, inverting gives us 11111110, and adding one gives us 11111111.

What about the max positive integer, which is 01111111, inverting gives us 10000000, and adding one gives us 10000001.

The reader is encouraged to practice other examples to grasp the full understanding of the Two's Complement Binary representation concept.

First Previous 1 Next Last

Yea, this works. So much effort, why can't they make it Justine format?

Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.