Custom Search
Phil Sykes
This is a class which has a member function that takes 3 arguements – std::string thestlstring, int base, and int base2. the function converts a number stored in the form of an std::string from the first base to the second. Bases 2 – 16 are supported.
massiveattack92(at)hotmail.com
/*******************************************************
* MYCPLUS Sample Code - http://www.mycplus.com *
* *
* This code is made available as a service to our *
* visitors and is provided strictly for the *
* purpose of illustration. *
* *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/
#include
#include
#include
#include "inputs.h"
inputs::inputs(std::string newstring, int newbase, int newbase2)
{
inpthenumber = newstring;
inpbase = newbase;
inpbase2 = newbase2;
}
inputs::~inputs(void)
{
}
std::string inputs::conv(std::string thestlstring, int base, int base2)
{
// variable declarations
int myval;
int remainder;
int loopvar = 0;
int mynumber = 0;
int testsum = 0;
float value1;
float value2;
char mychar;
char element;
std::string stlstring;
std::stringstream thestream;
// generate base 10 integer from number in base 'mybase'
string::iterator pos;
pos = thestlstring.end();
for (--pos;pos>=thestlstring.begin();--pos)
{
mychar = *pos;
switch (mychar)
{
case '0' :
myval = 0;
break;
case '1' :
myval = 1;
break;
case '2' :
myval = 2;
break;
case '3' :
myval = 3;
break;
case '4' :
myval = 4;
break;
case '5' :
myval = 5;
break;
case '6' :
myval = 6;
break;
case '7' :
myval = 7;
break;
case '8' :
myval = 8;
break;
case '9' :
myval = 9;
break;
case 'A' :
myval = 10;
break;
case 'B' :
myval = 11;
break;
case 'C' :
myval = 12;
break;
case 'D' :
myval = 13;
break;
case 'E' :
myval = 14;
break;
case 'F' :
myval = 15;
break;
}
mynumber += myval * (int)std::pow(base, loopvar);
++loopvar;
}
// generate 'n' - (n-1) = # of digits in base 10 number
// generated above
for (int n = 0;testsum < mynumber;++n)
{
testsum = testsum + (int)std::pow(base2,n) * (base2-1);
}
// declare array for insertion of digits from the
// converted number
char* revarray = new char[n-1];
// generate the new number
for (int i=0;i=0; --i2)
thestream << revarray[i2];
thestream >> stlstring;
// return the number
return stlstring;
}
//----------------------
//inputs.h
//----------------------
#include
class inputs
{
private:
std::string inpthenumber;
int inpbase;
int inpbase2;
public:
inputs(std::string, int, int); // called
// automatically when instance created
~inputs(void); // automatically called
// when object released from RAM
// must return void.
std::string conv(std::string thestlstring, int base, int base2);
};
Tags: C++ Programming, Source Code
There are No Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.