C++中的十进制到二进制转换年份

Decimal to Binary Converting Years in C++

我编写了一个将十进制数(出生日期)转换为二进制的程序。日期和月份的转换很顺利,但是在转换 时出现 问题,例如 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);
}

使用 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

或者,这段代码使用来自 STL 库的 std::bitset class。 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