Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to an integer using a given base

Tags:

c++

integer

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

int x = Integer.parseInt("0010011110", 2);
like image 689
learner Avatar asked Jan 15 '23 11:01

learner


2 Answers

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

int x = std::stoi("0010011110", nullptr, 2);
like image 125
pepper_chico Avatar answered Jan 28 '23 01:01

pepper_chico


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.

like image 32
Sergey Kalinichenko Avatar answered Jan 28 '23 02:01

Sergey Kalinichenko