unsigned int operator "" _b(const char* col, size_t n)
{
unsigned int result = 0;
int t;
for (int i = 0; i < n; i++) {
t = (col[n - 1 - i] - 0x30);
if (t != 0 && t != 1) throw std::string("literal error");
result+=t*pow(2, i);
}
return result;
}
int main(int argc)
{
int a = 0;
try {
cout << "11111111"_b << endl;
}
catch (std::string errinfo) {
cout << errinfo;
}
cin >> a;
return 0;
}
c++11 二进制字符串字面量解析为10进制
最新推荐文章于 2025-06-19 15:10:12 发布
本文介绍了一个C++函数,该函数能够将二进制字符串转换成无符号整数。通过遍历字符串并检查每个字符是否为'0'或'1',然后使用位运算和数学运算来计算最终的无符号整数值。如果字符串中包含除'0'和'1'之外的字符,函数会抛出一个异常。
1284

被折叠的 条评论
为什么被折叠?



