Programming & Scripting Tutorials

C++: Number Systems





This lesson is more a theory lesson (on number systems) rather than a lesson that teaches you tonnes more useful C++ stuff.

Alright so a number (187 for example) is in the decimal (dec) system; this system is based around 10. 187 reffers to the following:

187 = 1*100 + 8*10 + 7*1
This is because there is 1 hundred, 8 tens, and 7 ones.
This could also be written like so:

187 = 1*102 + 8*101 + 7*100

(Remember that anything to the power of 0 is 1!)
We are using 10 as the base as 10 is the base for the decimal system.

Other Number Systems



Octal



Ok so using 10 as the base number is what we're used to, but we can indeed have different base numbers (therefore creating different number systems).
If are number system had been invented by octopuses then we might have a number system based on 8. Mathematiclly this is called an octal system.
The octal system would display 123 like this(the lower (subscript) text indicates which base the number is using):

18710 = 2*82 + 7*81 + 3*80
18710 = 2738

Wondering how I got from the calculation to the octal number?
Just take the first number you multiply my the 8something in each step; take another look at the calculation:

18710 = 2*82 + 7*81 + 3*80

Also note that we count down the power number each time.
To output an octal number (and make C++ convert it to a decimal number) simply add a 0 to the front of the number.
For example the following would output 187:

cout << 0273;

Binary



Computers have basically "two fingers", they use the binary system which simply consists of 1's and 0's.
187 in binary would be this:

10111011

This is because of the following calculation:

18710 = 1*27 + 0*26 + 1*25 + 1*24 + 1*23 + 0*22 + 1*21 + 1*20

As you can see this begins to get a bit complicated and mathematical, but its worked out exactly the same as we worked the octal number out.
If you haven't figured it out yet the binary system has a base of 2.

Computers generally express binary numbers by using 4, 8, 16, 32, or 64 binary digits.
The term 'digit' refers to a multiple of 10, a binary digit is called a bit. A byte is made up of 8 bits, and computer memory is usually measured in bytes.

Hexadecimal



The octal system that we previously looked at has almost completely been replaced by the system we will be looking at now, the hexadecimal system.
The hexadecimal system uses 0-9 for the numbers 0-9, but then for numbers between 9-16 it uses the first six letters of the alphabet. For example A is 10, B is 11 etc.
Therefore we can write 187 as BB:

18710 = B*161 + B*160 = BB16

Programmers show a value is hexadecimal by adding the "0x" prefix, therefore the following would output 187:

cout << 0xBB;


This C++ tutorial was written by


Back to C++

Advertisement: