首页 > 解决方案 > 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 的补码中没有任何符号。我很困惑。

标签: c++strtolstrtoull

解决方案


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

推荐阅读