以下代码行的C++
等价物是什么Java
int x = Integer.parseInt("0010011110", 2);
std::stoi (C++11 起):
int x = std::stoi("0010011110", nullptr, 2);
您可以strtol
用来解析以 2 为底的整数:
const char *binStr = "0010011110";
char *endPtr;
int x = strtol(binStr, &endPtr, 2);
cout << x << endl; // prints 158
只需将strtol包装为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);