Thread: [First Program] Base Convertor

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    2

    [First Program] Base Convertor

    Hey guys, this is my first program i have written in C++ tell me what you think!!!
    It is a base convertor (yes, i know there is a method that does this, thought it would be good practice.)

    Im a intermediate to experienced java programmer, so my first program in C++ was pretty easy. Alot of the syntax is the same, the only thing i dont like about C++ is the way the arrays are setup, so as you can see, i used vectors(instead of lists, for the vector.at()).

    Any suggestions for my next C++ program/ comments on this one are much appreciated. Im not much familiar with pointers, i dont really see a point to them, if somebody could explain why i would use a pointer instead of accessing a var directly, that would be great too.

    Code:
    /*
    * @Author - Craig Naumann
    * @Date - 5 May, 2010
    * @Desc - Converters decimal numbers(base10) to other
    *         counting systems such as bin(base2) and hex(base16)
    */
    
    #include <string.h>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    vector<int> decToBase(int numb, int base);
    vector<char> decToHex(int numb);
    vector<int> decToBin(int numb);
    
    int main (){
      cout <<"Base Convertor" << endl;
      while(true){
        vector<int> vect;
        int in, conv2;
        string conv;
        cout <<"Enter a number to change base of: ";
        cin >> in;
        cout <<"Now enter a base to convert to(bin, hex, other): " ;
        cin >> conv;
        if(conv != "hex" && conv != "bin" && conv != "other"){
            cout << "Invalid selection" << endl;
            continue;
        }
        if(conv == "other"){
            cout  << "Base to use: ";
            cin >> conv2;
        }
    
        if(conv == "hex"){
            vector<char> vect2 = decToHex(in);
            for(int i = 0;i<vect2.size();i++){
                cout<< vect2.at(i);
            }
            cout << endl;
            continue;
        }else if(conv == ("bin"))
            vect = decToBin(in);
        else
            vect = decToBase(in,conv2);
    
        for(int i = 0;i<vect.size();i++){
            cout<< vect.at(i);
        }
        cout << endl;
      }
    
      return 0;
    }
    
    
    vector<char> decToHex(int numb){
        vector<int> start = decToBase(numb,16);
        vector<char> end;
    
        for(int i = start.size()-1;i>-1;i--){
            if(start.at(i)<10){
                end.push_back((char)(start.at(i)+48));
            }else {
                switch(start.at(i)){
                    case 10:
                        end.push_back('A');
                        break;
                    case 11:
                        end.push_back('B');
                        break;
                    case 12:
                        end.push_back('C');
                        break;
                    case 13:
                        end.push_back('D');
                        break;
                    case 14:
                        end.push_back('E');
                        break;
                    case 15:
                        end.push_back('F');
                        break;
                }
            }
        }
    
        return end;
    }
    
    vector<int> decToBin(int numb){
        vector<int> start = decToBase(numb,2);
        vector<int> end;
    
        for(int i = start.size()-1;i>-1;i--){
            end.push_back(start.at(i));
        }
    
        return end;
    }
    
    vector<int> decToBase(int numb, int base){
        int  rem = 0, dec = numb;
    
        vector<int> compNumb;
    
        do{
            rem = dec % base;
            dec = dec / base;
    
            compNumb.push_back(rem);
        }while(dec != 0);
    
        return compNumb;
    }

  2. #2
    ...and never returned. StainedBlue's Avatar
    Join Date
    Aug 2009
    Posts
    168
    variables can be passed by value (the way you're accustomed to) or by reference (by using references and pointers).

    Imagine passing around vectors/arrays of many large objects by value. That's a lot of info for the computer to handle. Much faster way is to pass by reference, meaning the *addresses* of those large objects can be used to manipulate them, without shuffling all their data as well.

    It's mostly a more efficient (in many cases, much more efficient) way of dealing with objects.

    There's also the difference between stack & heap memory, each has their merits, and i suggest you read up on that as well to help you understand better when to use pointers as opposed to references.

    EDIT: actually, in java things are passed by reference automatically, except for primitives. So java references are much like c++ pointers. So, think of it this way:
    Code:
    // java
    void myMethod(myObject foo){ /* ... */ } // automatically passed by ref
    
    // c++
    void myMethod(myObject& foo){ /* ... */ } // c++ way of passing by ref
    
    // using pointer
    void myMethod(myObject* foo({ /* ... */ } // also c++ way of passing by ref, but with pointer
    another thing to keep in mind is that in c++, pointers can be null, whereas references must be intialized, which is why i say java references are most like c++ pointers (java refs can be null)
    Last edited by StainedBlue; 05-05-2010 at 09:42 PM.
    goto( comeFrom() );

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    2
    Ahh, i get it. But for most programs on a computer, you wont really need them will you? Will you notice a difference in most programs? Ive had to deal with java heap memory, but that is when im dealing with an extremely large image(like 100,000X100 pixels).

    It would probably be good to get to know them, and i guess if your making a game, you will have so much data that u need pointers for the game to run correctly without lag, is that right?
    Thanks for you input btw.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The advantage of pass-by-pointer has been superseded by pass-by-reference, so that's not much of a reason any more (some code that is intended for both C/C++ will have to use pointers). As far as the stack goes, generally you get 1MB of stack (although you can dig into the system to change that), so anything that plans to use more than that is generally going to need memory from the heap.

    The containers mean we don't have to use new (and pointers) nearly so much as the equivalent C code for things like lists.

    If you intend to start writing classes that use polymorphism, you'll need pointers for that.

    EDIT: About the code: it seems like it would be a better thing to do the reverse in decToBase instead of in each of the other functions, especially since decToBase is callable from user code and they might get all confused. Note that reverse is built into the standard library, so you would probably want to do that instead of hand-rolling your own. (And if you do want to roll your own, there is reverse_iterator in a vector.)
    Last edited by tabstop; 05-05-2010 at 09:51 PM.

  5. #5
    ...and never returned. StainedBlue's Avatar
    Join Date
    Aug 2009
    Posts
    168
    well, it's just like java, except java does it for you.

    primitives = pass by value

    object = should be passed by reference

    Perhaps in trivial programs it doesn't make a huge performance difference, but if you're going to continue to program in c++, i'd sure invest the time in getting your brain wrapped around pointers/references.

    I'd estimate the vast majority of programs that were written in c++ that make it on to your computer make heavy use of pointers.

    And pointers are an *absolute must* for game programming.
    goto( comeFrom() );

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Along the same lines as the previous comment: in several places you're returning a vector from a function. This makes sense in Java, but in C++, the vector is actually stored on the stack (the way you've written it). So you end up making at least one complete copy of the vector, which isn't very efficient at all.

    There are a number of ways of getting around this. One way is that you can dynamically allocate the vector, putting it on the heap:
    Code:
    vector<int> *functionWhichReturnsAVector() {
        vector<int> *v = new vector<int>;
        // ...
        return v;
    }
    That's pretty awkward sometimes, though. Another way you can do it is to pass in the vector as a parameter, and then modify it that way.
    Code:
    void functionWhichReturnsAVector(vector<int> &v) {
        // ...
    }
    Just food for thought . . . .

    Also, instead of using 48, you can use the literal '0' directly. This is because C++ has much looser type coersion rules; you can take a char number and have it automatically converted to an int; you can use an int in an if statement:
    Code:
    int x = 3;
    if(x) {
        // ...
    }
    
    // equivalent to
    // if(x != 0)
    You can initialize doubles to ints and have the int automatically converted, etc. It's very convenient in some ways, but if you start playing around with that, definitely enable compiler warnings (yes, you typically have to enable them in C++). In fact, do that anyway.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Base Converter Part 2
    By encyclopedia23 in forum C Programming
    Replies: 2
    Last Post: 12-30-2006, 02:42 PM
  3. Bit Computation Program
    By cisokay in forum C++ Programming
    Replies: 6
    Last Post: 05-13-2005, 09:32 PM
  4. How to change number data from base 256 to base 16?
    By ooosawaddee3 in forum C++ Programming
    Replies: 2
    Last Post: 11-05-2002, 12:19 AM
  5. Virtual Base Class & Constructor :: C++
    By kuphryn in forum C++ Programming
    Replies: 2
    Last Post: 09-13-2002, 03:14 PM