Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,098 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,636 people online right now. Registration is fast and FREE... Join Now!




base conversions in C++

 
Reply to this topicStart new topic

base conversions in C++, understanding code syntax

nirvan25
15 Oct, 2007 - 12:46 AM
Post #1

New D.I.C Head
*

Joined: 23 Oct, 2005
Posts: 12


My Contributions
I found this working code at Base conversion in c++

it converts a base to decimal and vice versa. I would like to know how the functions biasetodec, dectobase and Getindex work. Especially the string manipulations done in them like (char* number),(char* szString), strcpy(chResult,_strrev(chResult));, strcpy(szString,chResult);.

Also, I do not understand how the use of the symbols A-Z were incorporated into the design.
Can someone please explain the code to me please.

CODE

#include "stdafx.h"
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

//Declarations:
//Takes a decimal number, converts it to base and stores the result in szString. Returns 1 on success or 0 on failure
int DecToBase(int,long,char*);
//Takes a number in any base and converts it to decimal.
//Number is a pointer to a string containing the value to convert (a string to allow for A-Z).
//Base is the base that number is in (e.g.16, if it is Hex)
int BaseToDec(char*,int);
//Returns position of a character in a string
int GetIndex(char *,char);

//Symbols used to display a number correctly
//Numbers over base 10 use letters to represent values over and equal to 10
//You should be able to increase the max no. of bases by adding other symbols
//Remember a string needs 1 extra space for null character
char symbols[37] = "0123456789ABCDEFGHIJKLMNoPQRSTUVWXYZ";
const int MAX_BASE = 36; //Highest base allowed (make sure there are enough symbols first!)
//

int main(int argc, char* argv[])
{
    char number[256] = "";
    cout << "Base conversion functions. Written by Matt Squire\n\n";
    //DecToBase samples
    cout << "Examples...\n\n";
    DecToBase(2,10,number);
    cout << "10dec to binary (base 2): " << number << endl;
    DecToBase(8,25,number);
    cout << "25dec to octal (base 8): " << number << endl;
    DecToBase(3,49,number);    
    cout << "240dec to base 36 (hexatridecimal?): " << number << endl;
    DecToBase(16,28,number);
    cout << "28dec to hexadecimal (base 16): " << number << endl;
    //I don't know why I wasted time working this one out... but 998453 spells LEET in base 36
    DecToBase(36,998453,number);
    cout << "998453dec to base 36: " << number << endl << endl;
    //BaseToDec samples
    cout << "4C9hex to decimal: " << BaseToDec("4C9",16) << endl;
    cout << "1760octal to decimal: " << BaseToDec("1760",8) << endl;
    cout << "1101011101bin to decimal: " << BaseToDec("1101011101",2) << endl << endl;
    //User input sample
    int iInput = 0,iBase = 2, iSrcBase = 10;
    cout << "Try another conversion...\nEnter a number in any base between 2 and 36 (must be integer): ";
    cin >> number;
    cout << "Enter a base to convert from: ";
    cin >> iSrcBase;
    cout << "Enter a base between 2 and 36 to convert to: ";
    cin >> iBase;
    //If the source base is not 10, convert it to 10 first
    if(iSrcBase!=10)
        iInput = BaseToDec(number,iSrcBase);
    else
        iInput = atoi(number);

    //If source base is not 10, and the destination base is, it is not nessecery to run DecToBase as the number
    //Has already been found in base 10
    if(iSrcBase!=10&&iBase==10)
    {
        cout << number << " in base " << iSrcBase << " = " << iInput << " in base " << iBase << endl << endl;
    }
    else
    {
        if(DecToBase(iBase,iInput,number))
            cout << iInput << " in base " << iSrcBase << " = " << number << " in base " << iBase << endl << endl;
        else
            cout << "Error: Base was out of bounds... (must be between 2 and 36)\n\n";
    }
    return 0;
}

int DecToBase(int base, long iDec, char* szString)
{
    //Check base is between 2 and 36
    if(base<2||base>MAX_BASE)
        return 0; //Failed
    //If input is 0, output is 0
    if(iDec==0){
        strcpy(szString,"0");
        return 1;
    }
    
    int count = 0;
    char chResult[256] = "";
    char* pChResult = chResult;
    while(iDec > 0 && count++<256)
    {
        *pChResult = symbols[iDec % base];
        pChResult++;
        iDec = iDec/base;    //iDec = itself divided by base
    }
    strcpy(chResult,_strrev(chResult));    
    strcpy(szString,chResult);

    return 1;
}

int BaseToDec(char* number, int base)
{
    if(base<2||base>MAX_BASE)
        return 0; //Failed

    int NumLength = strlen(number);
    int PlaceValue, total = 0;
    //Work out the place value of the first digit (base^length-1)
    PlaceValue = (int)pow(base,NumLength-1);
    
    //For each digit, multiply by its place value and add to total
    for(int i=0;i<NumLength;i++)
    {
        total += GetIndex(symbols,*number)*PlaceValue;
        number++;
        PlaceValue /= base; //Next digit's place value (previous/base)
    }
    return total;
}

//Finds the index of a particular character (if it exists) in an array. Returns last character on failure
//Used by BaseToDec to find face values
int GetIndex(char * pString, char search)
{
    int index = 0;
    while(*pString != (char)0) //Loop will finish at null character if no match is found
    {
        if(*pString==search)
            break;
        pString++;
        index++;
    }
    return index;
}




User is offlineProfile CardPM
+Quote Post

Xing
RE: Base Conversions In C++
15 Oct, 2007 - 01:33 AM
Post #2

D.I.C Addict
Group Icon

Joined: 22 Jul, 2006
Posts: 723



Thanked: 2 times
Dream Kudos: 1575
My Contributions
Author does gives a basic explanation of function he/she is implementing. You can take a look here also http://www.dreamincode.net/code/snippet729.htm
User is offlineProfile CardPM
+Quote Post

jjhaag
RE: Base Conversions In C++
15 Oct, 2007 - 02:01 AM
Post #3

me editor am smartastic
Group Icon

Joined: 18 Sep, 2007
Posts: 1,789



Thanked: 2 times
Dream Kudos: 775
Expert In: C,C++

My Contributions
for the string functions themselves, you may want to take a look at these two sites:

http://www.cppreference.com/stdstring/index.html
http://www.cplusplus.com/reference/clibrary/cstring/

the first is pretty spartan on the details, but if you're comfortable with pointer, array, and function syntax you may find it helpful as a quick reference. the second contains more detailed explanations of the functions, and generally some sample code (including the output, so you don't have to actually compile it to see the results of the programs).

check them out, then post if you have any more questions.

as for the use of the characters A-Z, these are necessary because for base N, you need N symbols for the digits of the numbers. in base 10 we can just use the "characters" 0-9. in base two it's 0 and 1. but if you are using base > 10, you need extra characters to represent the digits >9. for instance, hex uses 0-9 and A-F to represent the values 0-15:
CODE
hex        dec
0            0
1            1
2            2
...
9            9
A            10
B            11
...
F            15


hope that helps. if these responses didn't answer your question, please post again and clarify your query.

-jjh

User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/1/08 08:42PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month