[C++] - Number Systems to Decimal

Sajin

User title under construction.
Reaction score
56
So for my final project in my college principles of programming class, we were given an assignment where we are to take a hypothetical situation where we are to calculate the 'haul potential' of planets, if we were to mine them, by using (potential value)/(distance from headquarters) as our determining factor, the planet with the highest value is to be mined.

This stuff I'm perfectly content with. The problem arises when the coordinates of the planets can be entered in any number system between binary and hex, and thats where I get lost. I was hoping someone could shove me in the right direction.

I was thinking somewhere along the lines of making a loop that would find the (coordinate number) % (the base) then square that by a counter, then keep going like that, the problem comes with base 11 - 16.
 

Slapshot136

Divide et impera
Reaction score
471
so the input will look like:
base: n
coordinate: x

and for simplicity, it would be best to convert it into base 10, however lets first convert x into a string so we can reference each char as x[z]

x[base10] = x[length] * pow(n,length) + x[length-1] * pow(n, length-1) ... + x[0] * pow(n, 0)

and after you get the x coordinate in base 10.. you can repeat for y and z and then use Pythagorean theorem to figure out the direct distance ("as the crow flies doesn't seem to fit in space.."
)
that should work for any base.. I think, or are 11-16 like A-F?
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,675
Also, do consider that some intergalactic stellar will use number systems that's larger than base 16. For example, consider the Sexagesimal number system, originated from the Sumerians of the 3rd millennium BC.
 

Sajin

User title under construction.
Reaction score
56
for this assignment base 11 - 16 use A-F yes.
@tom_mai The assignment indicated it's only up to base 16 but I'll give it a shot once I get the base program working correctly.

Also correct me if im wrong, but wouldn't doing arithmetic with a char / string values end up using the ASCII value for the given number instead of the actual value?
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,675
Convert them to UTF, and be done with the low limit of 255.
 

Slapshot136

Divide et impera
Reaction score
471
if it's using A-F, then you need to convert that to 11-16.. shouldn't be too hard - what language will you be using exactly?
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
For C++

Code:
int HexToDec( char hex ){
    if( hex >= '0' && hex <= '9' )
        return  hex - '0';
    else if( hex >= 'A' && hex <= 'F' )
        return 10 + hex - 'A';
    else if( hex >= 'a' && hex <= 'f' )
        return 10 + hex - 'a';
    else throw std::exception(); //throw for numbers out of range
}
 
char DecToHex( int dec ){
    if( dec >= 0 && dec <= 9 )
        return '0' + dec;
    else if( dec >= 10 && dec <= 15 )
        return 'A' + dec - 10;
    else throw std::exception(); //throw for numbers out of range
}
 
std::string BaseXtoY( int baseFrom, int baseTo, std::string value ){
 
    if( value == "0" )
        return value; //0 is 0 in any base
 
    if( baseFrom <= 1 || baseTo <= 1 ) //base 1 and less is a no-no
        return "0";
 
    //Convert from X to decimal
    long long decimal = 0;
    int power = 1;
 
    for( auto it = value.rbegin(); it != value.rend(); ++it ){
        decimal += HexToDec(*it) * power;
        power*=baseFrom;
    }
 
    //convert from decimal to Y;
    value = "";
    power = baseTo;
 
    while( decimal > 0 ){
        char c = DecToHex( decimal % power );
        value.insert( value.begin(), c );
 
        decimal /= baseTo;
    }
 
    return value;
}

Example:
BaseXtoY( 16, 10, "123" ) returns "291"
Doesn't work for negative numbers, though.

It's a quick write-up. If you find bugs, please tell me :D
 

Sajin

User title under construction.
Reaction score
56
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
 
 
 
using namespace std;
 
const int IBMx = 6;
const int IBMy = 16;
const int IBMz = 1911;
 
void inPut();
 
int main()
{
 
int counter1;
int counter2;
int counter3;
int counter4;
int counter5;
 
 
 
 
ifstream inFile;
string fileName;
string data_input;
string temp_string;
vector<string> data;
vector<string> coordinates;
 
 
 
cout << "Please enter the file name: ";
cin >> fileName;
inFile.open(fileName.c_str());
 
while ( getline (inFile,data_input) )
        {
        data.push_back(data_input);
        temp_string = data[counter1].substr(0,1);
        if (temp_string == "(")
                {
                coordinates.push_back(data[counter1]);
                cout << coordinates[counter1];
                }
        counter1 = counter1 + 1;
 
        }

I keep getting a segmentation fault, and I'm derping on why... can anyone help me out on this? :3
 

Sajin

User title under construction.
Reaction score
56
After attempting to implement your code I got a few errors:

Code:
IBM2temp.cpp: In function ‘std::string BaseXtoY(int, int, std::string)’:
IBM2temp.cpp:63: error: ISO C++ forbids declaration of ‘it’ with no type
IBM2temp.cpp:63: error: cannot convert ‘std::reverse_iterator<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >’ to ‘int’ in initialization
IBM2temp.cpp:63: error: no match for ‘operator!=’ in ‘it != std::basic_string<_CharT, _Traits, _Alloc>::rend() [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]()’
IBM2temp.cpp:64: error: invalid type argument of ‘unary *’
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
I keep getting a segmentation fault, and I'm derping on why... can anyone help me out on this? :3


You haven't initialized counterX to a value. In C++, variables aren't automatically set to 0 when you create them.

Then it blows up because of this part:
Code:
temp_string = data[counter1].substr(0,1);
counter1 is some random (usually very big) number and everything is going haywire.

By the way, you can save yourself some trouble inside of that loop:

Code:
temp_string = data[counter1].substr(0,1);
        if (temp_string == "(")
                {
                ...
                }

can be changed to this if you only want a single character:

Code:
if( data[counter1] == '(' ) {
    ....

Or, if you want to take a longer part from data, you can write:

Code:
if( data[counter1.].substring(x,y) == "your string" ) {
...
 

Slapshot136

Divide et impera
Reaction score
471
I just came across something interesting in c++

you can just do this:

int i = 190;

cout << hex << i << endl;

and you get "be" as the output
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top