compsci-twos-compliment.html
* created: 2025-06-16T20:11
* modified: 2025-06-24T18:28
title
Two's Compliment
description
The Two's Compliment refers to a way of representing positiv an negativ numbers in binary.
I can handle negativity
The two's compliment refers to a mathematical method used in computing to represent signed integers in binary form. It allows for easy binary subtraction and supports both positive and negative numbers.
How to calculate?
Let's say we want to represent -7 in binary.
We first convert 7 into binary which looks like: 111_{2}.
We need at least 3 bit to represent the number 7. If we now wanted to represent the number in the one's compliment we would need at least 4 bits; 3 bits to represent the numbers from 0 to 7 and 1 bit to denote that it is a negative/positive number.
To get the representation of -7 in the one's compliment we just need to flip all bits 0111 = 7 -> 1000 = -7.
The problem with this representation is that we represent the number 0 twice; both 0000 and 1111 represent 0, which is not particularly efficient.
To mitigate this problem we can shift by one bit which allows us to represent the range from 7 to -8.
Our representation of the number -7 in the two's compliment looks like this: 1001