【问题标题】:Decimal to Binary Converting Years in C++在 C++ 中将十进制转换为二进制年份
【发布时间】:2021-12-26 05:31:39
【问题描述】:

我编写了一个将十进制数字(出生日期)转换为二进制的程序。转换日期和月份工作顺利,但是在转换 year 时会出现 问题,例如 2001 转换为 2521075409 而不是 11111010001。你能告诉我在哪里问题是什么?

{
    int i;
    long long temp, bin;

    i = 1;
    bin = 0;
    
    printf("Number %d in binary: \n", year);
    while (year > 0) {
        temp = year % 2;            
        year /= 2;              
        bin += temp * i;        
        i *= 10;                
    }
    printf("%lld\n\n",bin);
}

【问题讨论】:

  • 你超出了bin的大小。
  • 你可以使用std::bitset<>到二进制转换(reference)。

标签: c++ binary decimal converters


【解决方案1】:

使用int i;i *= 10 很快达到 32 位整数 0x7fff'ffff 的最大限制。所以i 也需要是 64 位的,它可以是unsigned,所以上限在0xffff'ffff'ffff'ffff 上有点高。示例

unsigned long long i = 1;
unsigned long long bin = 0;
int year = 2001;
while (year > 0) 
{
    int temp = year % 2;
    year /= 2;
    bin += temp * i;
    i *= 10;
    printf("check i: %llu\n", i);
}
printf("%016llu\n\n", bin);

要打印更大的数字,请在每次迭代中使用字符缓冲区来保存 temp

【讨论】:

  • 非常感谢!甚至没有注意到 i 已溢出。
【解决方案2】:

 或者,这段代码使用 STL 库中的 std::bitset 类。 bitset 表示 N bits 的固定大小序列。

string s = bitset<64>(2001).to_string();
     
// Strip off the leading zeroes.
const auto loc1 = s.find('1');
     
if(loc1 != string::npos) s= s.substr(loc1);

cout<<s<<endl; 

输出:

11111010001

完整的example

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 2012-12-26
    • 1970-01-01
    • 2019-03-24
    • 2019-04-26
    • 2018-05-10
    • 2012-06-26
    • 1970-01-01
    相关资源
    最近更新 更多