在字面意义上将字符串转换为 int

converting string to int in a literal sense

本文关键字:转换 int 字符串 意义上      更新时间:2023-10-16

你好:)我正在尝试使用 c++ 将字符串转换为 int。我尝试过使用 stol、stoll 和 strtol 函数(也许我用错了它们),但它们似乎并没有从字面意义上保留我的字符串。

问题:我将如何从字面上将包含 0 和 1 的字符串转换为 int,以便我的 int 与我的字符串完全相同

例:

string s = "00010011";
int digits = 0; // convert int to: digits = 00010011;

欣赏它!

好吧,你可以使用std::bitset

string s = "00010011";
int digits = 0; // convert int to: digits = 00010011;
std::bitset<32> bst(s);
digits = static_cast<int>(bst.to_ulong());

要对大小更加迂腐,而不是std::bitset<32>,您可以执行以下操作:

std::bitset<(sizeof(int) * 8)> bst(s);

要取回字符串(嗯,不完全是):

std::string sp = std::bitset<32>(digits).to_string();

此外,要从中修剪前导零,sp

auto x = sp.find_first_not_of('0');
if(x != string::npos)
    sp = sp.substr(x);