Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

complement
two
signed
number
binary

Why does two's complement work?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Two’s complement

Two’s complement is a technique for representing signed numbers in binary. The method representing a negative number is a simple two-step process:

  • Take the complement of the number’s positive counterpart
  • Add 11

The powerful thing about two’s complement representation is that we can perform arithmetic with the numbers as they are, and the answer we get will be the correct representation in two’s complement. But why does this simple technique work and result in such a mathematically consistent representation?

It is simply the result of subtracting the absolute value of the number from 0.0.

Let us see how this is true.

Subtraction from 00

Suppose we want to come up with a representation for -55 in binary. We know -55 is 55 less than 00, 050-5. We can try and compute this using the borrow method​ if we infinitely keep borrowing from the 00 on the left.

svg viewer

Although our answer will have a never-ending string of 11's at its left, we can simply truncate after 88 bits because that is all our computer will store – so this is our negative representation.

Now let’s follow the two’s complement method to find -55.

svg viewer

This is exactly the same as subtracting from 00 using the borrow method. Now you know what two’s complement does.

RELATED TAGS

complement
two
signed
number
binary
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring