Domanda

Ok so I'm currently trying to implement a MIPS program counter, which involves me storing a hex value to follow where the program is at (program counter). But the issue is the following code won't go past single digits as it increments i.e 0,4,8,0 etc. where the repeated 0 should equate to 10.

This source does work if str_pc is initally set to 00000010 but otherwise it will not.

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <map>

using namespace std;

string str_pc = "00000008";

int main(){
    int temp_pc;

    stringstream ss;
    ss << hex <<str_pc;
    ss >> dec >> temp_pc;
    cout << "Temp_PC: " <<temp_pc<<endl;
    temp_pc = temp_pc+4;

    ostringstream ss1;
    ss1 << hex << temp_pc;
    string x(ss1.str());

    str_pc = x;

    stringstream ss2;
    ss2 << hex <<str_pc;
    ss2 >> dec >> temp_pc;
    cout << "Temp_PC: " <<temp_pc<<endl;
    temp_pc = temp_pc+4;

    ostringstream ss3;
    ss3 << hex << temp_pc;
    string y(ss3.str());

    str_pc = y;

    cout << str_pc <<endl;
}

could anyone shine some light on what I'm doing wrong?

È stato utile?

Soluzione

hexadecimal is a representation of a number (integer) in a string.

ss << hex << str_pc;
ss >> dec >> temp_pc;

This does not make sense. The hex modifier in the first line does not work on strings, so is useless here. On the other hand on the second line you use a int so there you should put the hex modifier to make the string in the buffer interpreted as a hexadecimal number;

ss << str_pc;
ss >> hex >> temp_pc;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top