Alright I have a 32-bit string that is nothing but zeros and ones. Each 5 bits represents a different section of the instruction format. Then the last section will have 7 bits (the leading two are fillers).
Here's an example:
1 2
im1.store("10111000010000100010000110000000", 1); // Storing 32-bit string into index 1 of Instruction Memory
string binary = im1.fetch(count); // Fetching that string and storing into string variable binary
So num1 = binary.substr(0, 5) is going to be "10111" in this scenario.
1 2 3 4 5
num1[0] = 1;
num1[1] = 0;
num1[2] = 1;
num1[3] = 1;
num1[4] = 1; // Just showing what each bit will be. Still string though
However, it is still a string. How can go about turning each string bit into an int (there will only be zeros and ones still) that way I can do a binary to decimal conversion? I've tried atoi, and strtol, but nothing seems to be working out. I deleted my previous post, because I don't feel that I asked the question correctly.
calculating an number from a string consisting '1s' and '0s' to an integer is simple enough;
1 2 3 4 5 6 7 8 9
string binaryStr("0011");//some string or the other
int result =0 ;
for(size_t count = 0; count < binaryStr.length() ; ++count)
{
result *=2;
result += binaryStr[count]=='1'? 1 :0;
}
You can certainly use strtol for this purpose. Go through the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <string>
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main (void)
{
string str = "11001"; // binary representation of 25.
cout << strtol (str.c_str (), NULL, 2) << endl;
// The third argument of strtol is the base of the number system.
return 0;
}
bitset has a better interface than strtol() because it will throw if the input is invalid. While you can detect errors with strtol(), it is clumsy to use and commonly ignored.