c++ - walk, strol 函数没有为 long_min 提供正确的输出
问题描述
对于以下代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
bitset<64>b(numeric_limits<long>::min());
string s=b.to_string();
char *ptr=new char [s.size()+1];
strcpy(ptr,s.c_str());
long l1=strtol(ptr,NULL,2);
cout<<"l1= "<<l1<<endl;
long l2=strtoul(ptr,NULL,2);
cout<<"l2= "<<l2<<endl;
cout<<strtoul(ptr,NULL,2)<<endl;
}
输出是
l1= 9223372036854775807
l2= -9223372036854775808
9223372036854775808
为什么l1
不是long_min
,为什么是l2
?我读过该字符串可以在 ato*,strto* 函数的开头包含+
/-
符号。-
但是二进制中的负数在计算机使用的 2 的补码中没有任何符号。我很困惑。
解决方案
ERANGE
提供大于 along
可以容纳的正值时会出现错误。要使其与您一起使用,strtol
您需要添加一个-
:
#include <bitset>
#include <cstring>
#include <iostream>
#include <limits>
#include <string>
int main()
{
std::bitset<64> b(std::numeric_limits<long>::min());
std::string s = "-" + b.to_string();
long l1=strtol(s.c_str(), NULL, 2);
std::cout << "l1= " << l1 << '\n';
}
可能的输出:
l1= -9223372036854775808
推荐阅读
- mysql - SphinxQL 连接问题(守护进程正在监听时)
- avro - 如何在 Avro 模式中指定范围?
- javascript - 在 Angular 6 中动态调用索引组件
- node.js - Let's Encrypt 的证书无法与 node.js 一起使用
- angular - 在表之间添加动态行
- azure - Azure 中的安全存储服务是什么?
- azure - 在 Azure Function 中接收服务总线消息
- python - django,角度,csrf,rest_framework,403,
- c++ - 如何在 MFC 应用程序中添加文档菜单?
- java - 为什么我没有得到任何输出?并且有一个 InputMismatchException