在字面意义上将字符串转换为 int
converting string to int in a literal sense
你好:)我正在尝试使用 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);
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 将 int 数组转换为 std::vector<int*>
- 如何转换 int 变量并附加到常量 wchar_t*
- 类型转换<int>的舍入问题
- 在Objective-C中调用sqlite3数据库时,如何调用和转换int/NSNumber
- 转换 int -> 无符号长 长 是否由标准定义
- 简单的 int 到字符串转换..int to const char* 无效
- 如何将转换 int 除法键入为浮点数
- C++类型转换 int * 到类
- 预期的类型说明符,并且无法在初始化时转换“int*”
- 转换int并将其与char*连接
- 字符串流在转换int型时添加新行
- 转换int为字符串/char c++ /Arduino
- c# P-Invoke:如何转换INT fun(BYTE *bStream, UINT16 *nCount, const
- 类型转换(int**)和int(*)的区别
- 从"int"到"nodeType"的无效转换<int>
- 从无符号int构造对强制转换int的引用