Bit Representation

From Dev Wiki
Revision as of 14:01, 2 February 2020 by Brodriguez (talk | contribs) (Create page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Two's Compliment

Also known as "signed integer" representation.

At the bit level, everything is computed and stored the same as unsigned.
However, when representing the number to the user, it's handled differently.

Effectively:

  • Check the largest (leftmost) bit.
    • If it's 0, then compute normally, the same as unsigned.
    • If it's 1, the value is negative, so proceed to the next steps.
  • Drop off the largest (leftmost) bit, as we know the value is negative.
  • Invert remaining bits.
  • Add 1 to these inverted bit.
  • Read in new value as your number, as a negative.

Two's Compliment Examples

Positive Example: 0110

We read this in normally, so we would have:
0 + 4 + 2 + 0 = 6
Our resulting value is 7.

Negative Example: 1110

Our leftmost bit is 1, so we know it's negative.
First, we drop this leftmost bit, giving us 110.
Next, we invert our bits, giving 001.
Now we add 1 to our inverted value:

 001
+  1
 ---
 010

Our final binary value is 010. We can now read this as a negative number, giving:
-(0 + 2 + 0) = -2
Our resulting value is -2