-
C++ Types 2
Posted on May 1st, 2009 1 commentEncoding Numbers
To start of with we will want to store numbers. Let’s assume we want to store unsigned integers. Believe it or not there are many ways of encoding unsigned integers into bits.
The simplest method I can imagine is the following, we could encode the number by the number of sequential 1 bits, e.g. 1 is 1, 11 is 2, 111 is 3, 1111 is 4 etc. Use 0 as a marker for the end of the number and we have 10 is 1, 1110 is 3 and 1111111110 is 9. You could represent any number using this scheme. The major disadvantage of this method is that the space used to represent the number is the same as the magnitude of the number. This means it will take 1 Megabit to represent the number 1048576. To resolve this we need to use a positional notation to represent a number.
There is also a system called Binary Coded Decimal (BCD) where each decimal digit is stored in a nibble (4 bits) .
0
1
2
3
4
5
6
7
8
9
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
So 1234 would be 0001001000110100
However these are both stupid ways of doing it (Although BCD has its uses) the usual way is just called binary encoding and works just like our decimal system except with 2 digits , 0 and 1.
So for 123456 in decimal and 53 in binary (110101):
123456 means:
123456 in decimal
= 1*100000 + 2*10000 + 3*1000 + 4*100 + 5*10 + 6
= 1*10*10*10*10*10 + 2*10*10*10*10 + 3*10*10*10 + 4*10*10 + 5*10 + 6110101 means:
53 in decimal
= 1*32 + 1*16 + 0*8 + 1*4 +0*2 + 1
= 1*2*2*2*2*2 + 1*2*2*2*2 + 0*2*2*2 + 1*2*2 + 0*2 + 1C++ only uses normal binary encoding for unsigned integers. If you want to use your own encoding you’ll have to create your own type to do it.
Happy Programming
One response to “C++ Types 2”
-
[...] This post was Twitted by engineerfinder – Real-url.org [...]
Leave a reply
-


