Computer Conversions

 < Day Day Up > 

Often, you hear people talk about 50-kilobyte files or 2-gig hard drives . These might sound like random numbers . It's important to understand how all these quantities are related . They all describe quantities of information that the computer can read or store. Remember that the computer actually reads binary code.

When you program code in a language such as C++, you need a compiler to translate your code into binary code. Then the computer flips a bunch of switches on (1) or off (0). Binary code is simply a series of 0s and 1s that state whether each individual switch is currently on or off. Each of these switches holds 1 bit of information: 0 or 1. Then these bits can be grouped into sets of eight, which is 1 byte of information. Each byte can be used to represent a number between 0 and 255. Here's where it gets tricky.

In "The Metric System" section, you saw how easy it was to work with a base-10 system. The decimal system is base 10. Each digit represents a power of 10. You might remember learning about the 1s digit, the 10s digit, the 100s digit, and so forth back in grade school. Now imagine that each digit represents a power of 2 rather than 10; that's how the binary system is set up. Table 7.2 compares decimal digits to binary digits.

Table 7.2. Digits in Decimal (Base 10) Versus Binary (Base 2)

Decimal (Base 10)

10 7

10 6

10 5

10 4

10 3

10 2

10 1

10

10,000,000

1,000,000

100,000

10,000

1,000

100

10

1

Binary (Base 2)

2 7

2 6

2 5

2 4

2 3

2 2

2 1

2

128

64

32

16

8

4

2

1

In the decimal system, a number like 702 is really 7 100s plus 0 10s plus 2 1s. In the binary system, each digit is worth a power of 2 rather than a power of 10. This means that the number 10011010 in binary is really one 128 plus no 64s plus no 32s plus one 16 plus one 8 plus no 4s plus one 2 plus no 1s, which is really 128 + 16 + 8 + 2 = 154 as a decimal number. Table 7.3 illustrates the binary digits for the number 10011010.

Table 7.3. The Binary Number 10011010

2 7

2 6

2 5

2 4

2 3

2 2

2 1

2

128

64

32

16

8

4

2

1

1

1

1

1

128

16

8

2

Example 7.7: Converting Binary to Decimal

Convert the binary number 01001101 to decimal.

Solution
  1. The easiest approach is to use a table like this to organize the binary digits:

    2 7

    2 6

    2 5

    2 4

    2 3

    2 2

    2 1

    2

    128

    64

    32

    16

    8

    4

    2

    1

    1

    1

    1

    1

    64

    8

    4

    1

  2. Add the numbers in the bottom row:

    64 + 8 + 4 + 1 = 77

The binary number 01001101 is equal to 77 in decimal form.

If all eight digits are 0s, that's the equivalent of 0 in decimal. If all eight digits are 1s, that's the equivalent of 255 in decimal form. A unique binary number can represent each of the numbers between 0 and 255. The process of converting a number from decimal to binary can best be described with an example.

Example 7.8: Converting Decimal to Binary

Convert the decimal number 185 to binary.

Solution
  1. Find the largest power of 2 that's less than 185. (The preceding table lists the first eight digits.) In this case, 128 is the largest power of 2 that is less than or equal to 185.

  2. Subtract 128 from 185, which gives you 57.

  3. Repeat the process using 57. The largest power of 2 that's less than or equal to 57 is 32.

  4. Subtract 32 from 57, and you're left with 25.

  5. Keep repeating the process until you reach 0.

  6. The largest power of 2 that's less than or equal to 25 is 16.

  7. Subtract 16 from 25, which leaves you with 9.

  8. The largest power of 2 that's less than or equal to 9 is 8.

  9. Subtract 8 from 9, and you get 1.

  10. The largest power of 2 that's less than or equal to 1 is 1.

  11. Subtract 1 from 1, and you get 0. Now you can stop.

  12. The last step is to go through the list and, for every number you subtracted, give its corresponding digit a 1. For all the other powers of 2 that got skipped , give their digits a 0. You end up with the following:

    2 7

    2 6

    2 5

    2 4

    2 3

    2 2

    2 1

    2

    128

    64

    32

    16

    8

    4

    2

    1

    1

    1

    1

    1

    1

This means that the binary number 10111001 is the same as decimal number 185.

Programming Binary and Decimal Conversions

The process of converting from binary to decimal and back again is a slightly different process in code than it is on paper. The algorithm works the same, but there are important things that have to be adjusted so that they work within the computer and still give the user the correct expected value from the conversion. First let's take a look at converting decimal to binary:

 void decimaltoBinary()     {       int tobeconverted;       int binaryplaceholder[32];       cout<<"Please enter a binary number in ones and zeros\n";       cin>>tobeconverted;       for(int i =0;i<32;i++)        {          //take the number and process modulus to return a 1 or 0             binaryplaceholder[i] = tobeconverted%2;          //then we divide the number by two and revisit the number.          tobeconverted = tobeconverted/2;        }    cout<<"Your decimal number converted to binary is: \n";        //To make sure we are outputting in the proper order,        //we print the array backwards.        for(int j = 31; j>=0;j--)         {           cout<<binaryplaceholder[j];         }     } 

First, the code takes a valid binary input. Then using the modulus operator, the number is determined to be currently even or odd (1 or 0) and the resulting value is stored in the binaryplaceholderarray , slowly constructing the converted number. Then we divide the number by two and continue the process. The last part of this function prints out the new binary number from left to right. In order to maintain the proper ordering of the binary number, it starts from the end and prints backwards. Pretty cool, eh?

Now let's look at the conversion process to turn a binary number into a decimal number. This process is similar, but requires us to use some additional tools:

 void binarytoDecimal()     {       char tobeconverted[9];       int finalvalue =0;       int powerval = 0;       cout<<"Please enter a binary value (8 bits max) MSB first.\n";       cin>>tobeconverted;       //run from 0-7 = 8 bits total       for(int j = 0; j<=7; j++)        {          //we have to reverse the power so the ordering is MSB first,          powerval = pow(2,(7-j));          //test for a "1", otherwise it must be a zero.          if(tobeconverted[j] == '1')             finalvalue = finalvalue + powerval;        }        cout<<"The number from binary to decimal is graphics/ccc.gif <<finalvalue<<"\n";      } 

This function first takes in an 8-bit binary value. 8 was chosen so the conversion could more easily be demonstrated. Feel free to increase the number of bits if you like; the algorithm is the same. Once the binary number is in the char[] , we move through one position at a time, calculating the current power of 2, then test to see if the value that is to be converted is a 1. If so, add the final-value to the powerval . The reason that we don't need to ask if its zero is because in a binary situation a number that is not one is always zero, or invalid. Since the Most Significant Bit (MSB) is the first one to come into the array, it has to have the highest possible power of the entire binary number. It is very easy to ignore this step and have the values in the reverse ordering giving incorrect values. These sort of conversions should always trap errors to keep from long debugging sessions. Make sure your code does.


From the unit of bits, you can build conversions to all the other binary units. Let's start with the smallest units and work our way up. I said earlier that a byte of information is equal to 8 bits. Most files such as text documents consist of thousands of bytes of information. It can be cumbersome to work with such large quantities, so often we convert them to kilobytes. One kilobyte equals 1,024 bytes. Some files, particularly those with many graphics, are much larger, so it might make sense to convert to an even larger unit, the megabyte. One megabyte equals 1,024 kilobytes. Let's take this thought one step further. Often, hard drives are described by the amount of information they can store. The most sensible unit for that is the gigabyte. One gigabyte equals 1,024 megabytes. All this information can be summarized as follows :

1 byte = 8 bits

1 kilobyte = 1,024 bytes

1 megabyte = 1,024 kilobytes

1 gigabyte = 1,024 megabytes

NOTE

These conversion factors might seem odd. Remember that you're working with binary now, which is base 2. That is why the conversion factors must be powers of 2.


The actual conversion process is the same as we discussed in the last section. You just have a new set of conversion factors this time. Let's look at an example.

Example 7.9: Computer Conversion

If your computer hard drive holds 20GB of information, how many bits is that?

Solution
  1. Start with the original quantity, 20GB.

  2. Stack to the right a series of conversion factors that will convert gigabytes to bits. Try to keep the fractions lined up so that you're less likely to make a mistake when you go back to multiply:

    graphics/07equ10.gif


  3. Make sure that the fractions are flipped in such a way that the units cancel the way you want.

  4. Multiply all the fractions:

    graphics/07equ11.gif


One of the distinctive features of C++ is that it allows you to allocate memory as the application runs. If that's the case, you must be precise about the amount of space you need. If you're trying to get a rough estimate in your head, you can round the conversion factors to just 1,000, but if you're allocating memory or dealing with storage issues, it's imperative that you use 1,024 for all the conversion factors. If you're off by even a single byte, the program could crash. That is why these computer conversions are extremely important.

Self-Assessment

1.

Convert the binary number 10101010 to decimal.

2.

Convert the binary number 01101101 to decimal.

3.

Convert the decimal number 176 to binary.

4.

Convert the decimal number 205 to binary.

5.

How many bits of information can be stored on a 100MB zip disk?

6.

If you allocate 4KB of storage space, how many bits can it hold?

7.

If you have a file that's 12,345,678 bits large, how many megabytes is that?

8.

How many gigabytes are in 23,753,891,429 bytes?


 < Day Day Up > 


Beginning Math and Physics for Game Programmers
Beginning Math and Physics for Game Programmers
ISBN: 0735713901
EAN: 2147483647
Year: 2004
Pages: 143
Authors: Wendy Stahler

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net