Convert string to integer using given base

What is the C++ equivalent of the next line of Java code

 int x = Integer.parseInt("0010011110", 2); 
+4
source share
4 answers

You can use strtol to parse an integer in base 2:

 const char *binStr = "0010011110"; char *endPtr; int x = strtol(binStr, &endPtr, 2); cout << x << endl; // prints 158 

Here is a link to a demo on ideone .

+1
source

std :: stoi (since C ++ 11):

 int x = std::stoi("0010011110", nullptr, 2); 
+7
source

Just end strtol as parseInt

 #include <stdio.h> #include <stdlib.h> int parseInt(const std::string& s, int base) { return (int) strtol(s.c_str(), null, base); } int x = parseInt("0010011110", 2); 
+1
source

atoi or better still strtol

 long x = strtol("0010011110",nullptr, 2); 
0
source

All Articles