# Twos complement

## Introduction

In the binary system, there are two possible values for each digit: 0 and 1. This means that we can represent positive integers by simply writing them in binary notation, where the most significant bit (MSB) represents the sign (0 for positive, 1 for negative) and the rest of the bits represent the magnitude.

For example, the binary representation of the positive integer 5 is 0101. However, to represent negative integers, we need a different system that allows us to perform arithmetic operations such as addition and subtraction.

## Two’s Complement Representation

The two’s complement representation of a number is obtained by taking the binary complement (flipping all the bits) of the number and adding 1. In other words, to represent the negative of a number in binary, we invert all its bits and then add 1.

For example, the two’s complement representation of -5 is obtained as follows:

1. Write the binary representation of 5: 0101.
2. Invert all the bits: 1010.

Therefore, the two’s complement representation of -5 is 1011.

In general, the two’s complement representation of a negative number can be obtained as follows:

1. Write the binary representation of the absolute value of the number.
2. Invert all the bits.

For example, the two’s complement representation of -10 is obtained as follows:

1. Write the binary representation of 10: 1010.
2. Invert all the bits: 0101.

Therefore, the two’s complement representation of -10 is 0110.

## Arithmetic Operations

Once we have the two’s complement representation of two numbers, we can perform arithmetic operations such as addition and subtraction by simply adding or subtracting the binary numbers, ignoring any overflow.

For example, let’s add -5 and -10:

1. Write the two’s complement representation of -5: 1011.
2. Write the two’s complement representation of -10: 0110.
3. Add the two binary numbers 1011 + 0110 = 0001
4. Ignore any overflow beyond the width of the binary number. In this case, the result is positive, so the sign bit is 0, and the magnitude is 0001, which represents the decimal number 1.

Therefore, -5 plus -10 equals -1 in two’s complement representation.

## Conclusion

Two’s complement is a useful and widely used representation of signed integers in computer systems. It allows us to perform arithmetic operations with negative numbers using the same logic as with positive numbers. By understanding how two’s complement works, undergraduates can gain a deeper understanding of computer architecture and programming.