String array to int

I have a binary string that I am trying to convert into a decimal. In order to do that I have to access each number (0, 1) in the string. The num1 string = "00001" after the sub-string

Here's my code:
1
2
3
4
5
6
7
8
string num1 = b.substr(0, 5); // Grabbing the first 5 bits of the 32-bit string
num1[1] = atoi(num1[1].c_str()); // Want to get each index of the string converted to int..this does not work

// Decode each sub-string
double dec1 = ((num1[0] * 0) + (num1[1] * pow(2.0, 3)) + (num1[2] * pow(2.0, 2))
+ (num1[3] * pow(2.0, 1)) + (num1[4] * pow(2.0, 0))); // Binary to Decimal

cout << dec1 << " " << num1[1] << " " << ((num1[1]) * (pow(2.0, 3.0))) << " " << (0 * (pow(2.0, 3.0))) << endl;


Last edited on
I understand how the atoi works, but it's not allowing me to access and assign each string index.
std::cout << std::strtol("00101010001010100011000000000000", 0, 2) << std::endl;

and if you want to support numbers larger than (2^31-1):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
unsigned long long str2ull(const std::string & s)
{
   std::string::const_reverse_iterator it  = s.rbegin();
   std::string::const_reverse_iterator end = s.rend();

   unsigned long long factor = 1;
   unsigned long long result = 0;

   for(; it != end; ++it)
   {
      switch(*it)
      {
         case '0':
            factor *= 2;
            break;

         case '1':
            result += factor;
            factor *= 2;
            break;
      }
   }

   return result;
}

int main()
{
   std::cout << str2ull("11000000_11110000_11000011_10100101_00101010_00101010_00110000_00000000") << std::endl;

   return 0;
}
Last edited on
The only problem with that is each 5 bits needs to be separate from the others. The last instruction will be 7 bits long, with the last 2 being fillers. So I need to convert each bit to from string (zero or one) to int (zero or one).
You could simply do something like this: strtol(b.substr(0, 5).c_str(), 0, 2)
closed account (S6k9GNh0)
If I'm not mistaken, there should be custom numeric classes to handle things like this. There was a contest not to long ago on the forums containing BIG NUMs.
Last edited on
Abramus is right , soory but why need custom numberic class when this can be done in a single line .strtol(b.substr(0, 5).c_str(), 0, 2)
So would it be num1 = strtol(b.substr(0, 5).c_str(), 0, 2); then num1[1] will be an int instead of a string...?
strtol returns a long. You cannot assign it to a string variable.
Topic archived. No new replies allowed.