How is an integer stored in memory?

It’s represented in binary (base 2). Read more about number bases. In base 2 you only need 2 different symbols to represent a number. We usually use the symbols 0 and 1. In our usual base we use 10 different symbols to represent all the numbers, 0, 1, 2, … 8, and 9.

For comparison, think about a number that doesn’t fit in our usual system. Like 14. We don’t have a symbol for 14, so how to we represent it? Easy, we just combine two of our symbols 1 and 4. 14 in base 10 means 1*10^1 + 4*10^0.

1110 in base 2 (binary) means 1*2^3 + 1*2^2 + 1*2^1 + 0*2^0 = 8 + 4 + 2 + 0 = 14. So despite not having enough symbols in either base to represent 14 with a single symbol, we can still represent it in both bases.

In another commonly used base, base 16, which is also known as hexadecimal, we have enough symbols to represent 14 using only one of them. You’ll usually see 14 written using the symbol e in hexadecimal.

For negative integers we use a convenient representation called twos-complement which is the complement (all 1s flipped to 0 and all 0s flipped to 1s) with one added to it.

There are two main reasons this is so convenient:

  • We know immediately if a number is positive of negative by looking at a single bit, the most significant bit out of the 32 we use.

  • It’s mathematically correct in that x - y = x + -y using regular addition the same way you learnt in grade school. This means that processors don’t need to do anything special to implement subtraction if they already have addition. They can simply find the twos-complement of y (recall, flip the bits and add one) and then add x and y using the addition circuit they already have, rather than having a special circuit for subtraction.

Leave a Comment