【问题标题】:Convert binary string to int with same representation将二进制字符串转换为具有相同表示的 int
【发布时间】:2017-12-29 04:39:54
【问题描述】:

我有一个问题,如何在 C++ 中通过保持数字的相同表示来将二进制字符串转换为 int?比如我想把这个字符串“0000”转换成这个int 0000。

当我使用这个时:

string str = "0000" ;
int num = atoi(str.c_str());
cout <<num << endl;

我得到了数字 0,但我想要数字 0000。

【问题讨论】:

  • int 存储一个数值。 0000000000000 都具有相同的数值 - 零。您无法单独在int 中保留区别。如果区别很重要,请将其保留为string
  • 我想保留区别,因为我正在使用整数掩码我必须在一些数字之间做一些比较,而且我不知道如何使用字符串掩码。这是我的另一个问题:stackoverflow.com/questions/48000038/…
  • @RedOne 掩码00000一样,没有区别。
  • 那么我必须使用字符串掩码,你能看到我的其他问题以了解我想要实现的目标并给我一个简短的例子来告诉我如何使用字符串掩码吗?这是我的问题:stackoverflow.com/questions/48000038/…

标签: c++ string type-conversion int


【解决方案1】:

您将使用setfill 操纵器添加格式化逻辑。

#include <iostream>
#include <iomanip>

int main()
{

  for(int n = 0; n <= 1000; n = n + 100)
  {
    std::cout << "default: " << std::setw(4) << n << '\t'
      << "setfill('0'): " << std::setfill('0')
      << std::setw(4) << n << '\n';
  }

  return 1;
}

这将产生以下输出:

default:    0   setfill('0'): 0000 <-- Desired formatting when value is 0
default: 0099   setfill('0'): 0099
default: 0198   setfill('0'): 0198
default: 0297   setfill('0'): 0297
default: 0396   setfill('0'): 0396
default: 0495   setfill('0'): 0495
default: 0594   setfill('0'): 0594
default: 0693   setfill('0'): 0693
default: 0792   setfill('0'): 0792
default: 0891   setfill('0'): 0891
default: 0990   setfill('0'): 0990

【讨论】:

  • 这是个好主意,谢谢,我会尝试从这个开始。
猜你喜欢
  • 2013-01-30
  • 2011-01-25
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多