# 5.1: Representing integers


You probably know that computers represent numbers in base 2, also known as binary. For positive numbers, the binary representation is straightforward; for example, the representation for $$5_{10}$$ is $$b101$$.

For negative numbers, the most obvious representation uses a sign bit to indicate whether a number is positive or negative. But there is another representation, called “two’s complement” that is much more common because it is easier to work with in hardware.

To find the two’s complement of a negative number, $$-x$$, find the binary representation of $$x$$, flip all the bits, and add 1. For example, to represent $$-5_{10}$$, start with the representation of $$5_{10}$$, which is $$b0000\ 0101$$ if we write the 8-bit version. Flipping all the bits and adding 1 yields $$b1111\ 1011$$.

In two’s complement, the leftmost bit acts like a sign bit; it is 0 for positive numbers and 1 for negative numbers.

To convert from an 8-bit number to 16-bits, we have to add more 0’s for a positive number and add 1’s for a negative number. In effect, we have to copy the sign bit into the new bits. This process is called “sign extension”.

In C all integer types are signed (able to represent positive and negative numbers) unless you declare them unsigned. The difference, and the reason this declaration is important, is that operations on unsigned integers don’t use sign extension.

This page titled 5.1: Representing integers is shared under a CC BY-NC license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .