C Tutorial


Hexadecimal and Octal
number systems


The octal and hex number systems are actually quite easy, and i'll explain why we actually use them for programming.

Now, lets take a look at our own number system, we have digits ranging from 0 to 9.

If we look at a number

9

that translates into well 9.

86

this translate into 8 * 10 + 6 * 1.

Then

475

4 * 100 + 7 * 10 + 5 * 1

you'll see a pattern here,

note '^' is 'the power of'

9 = 9 * 10 ^ 0

86 = 8 * 10 ^ 1 + 6 * 10 ^ 0

475 = 4 * 10 ^ 2 + 7 * 10 ^ 1 + 5 * 10 ^ 0

So it from left to right, using the base (10) the power raises by 1 and you times that by the digit.

So oct and hex are the same

In oct we have 8 digits 0 - 7
and to translate octal numbers into decimal numbers

46 = 4 * 8 ^ 1 + 6 * 8 ^ 0
456 = 4 * 8 ^ 2 + 5 * 8 ^ 1 + 6 * 8 ^ 0

Then hex, we have the digits 0 - 9, with the additional digits from A - F

A - 10
B - 11
C - 12
D - 13
E - 14
F - 15

exactly the same procedure

47A = 4 * 16 ^ 2 + 7 * 16 ^ 1 + 10 * 16 ^ 0
AFD = 10 * 16 ^ 2 + 15 * 16 ^ 1 + 13 * 16 ^ 0

Now why do we use these number systems? Well, they easily translate into binary since they are a mulitple of 2.

In octal, each digit will translate into 3 binary digits

0 - 000
1 - 001
2 - 010
3 - 011
4 - 100
5 - 101
6 - 110
7 - 111

Very easy,

463 - 100 110 011

and put together

142 - 001100010

and hex is the same accept each digit represents 4 binary digits

0 - 0000
1 - 0001
2 - 0010
3 - 0011
4 - 0100
5 - 0101
6 - 0110
7 - 0111
8 - 1000
9 - 1001
A - 1010
B - 1011
C - 1100
D - 1101
E - 1110
F - 1111

473 - 0100 0111 0011
6FA - 0110 1111 1010

So you see why it's very good to use hex and octal in programming, sometimes we aren't worried about the value of the decimal number, using bit wise operations, we are only interested in the locations of the 1's and 0's in a binary number

One last thing, to use octal and hex numbers in C

Octal we just have a 0 infront of the number

0345 - octal number 345
0153 - octal number 153

And in Hex we put 0x infront of the number

0x3F7 - hex number 3F7
0x2H7 - hex number 2H7

To have printf print out in hex and oct
you have the operators to do so

%0x - hex
%o - oct

simple :)


©2005 Kyro