[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,667
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,667
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 The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1
  • The Helper The Helper:
    The recipe today is Sloppy Joe Casserole - one of my faves LOL https://www.thehelper.net/threads/sloppy-joe-casserole-with-manwich.193585/
  • The Helper The Helper:
    Decided to put up a healthier type recipe to mix it up - Honey Garlic Shrimp Stir-Fry https://www.thehelper.net/threads/recipe-honey-garlic-shrimp-stir-fry.193595/
  • The Helper The Helper:
    Here is another comfort food favorite - Million Dollar Casserole - https://www.thehelper.net/threads/recipe-million-dollar-casserole.193614/

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top