string MySystem::DecToBinary(int n)
{
//因为要处理负数的情况,且负数和正数的不对称性,所以需要将其转换为大数
//第一种,我们可以使用常规的方法来求解,即取2的模数,然后除以2.....如此循环,得到结果
long long Temp = static_cast<long long>(n);
if (Temp<0)
{
//处理补码的情况
Temp = UINT_MAX + n + 1;
}
string Result("");
while (Temp)
{
Result += (Temp % 2 + '0');
Temp /= 2;
}
//翻转字符串
int i = 0;
int j = Result.size() - 1;
while (i<j)
{
swap(Result[i], Result[j]);
++i;
--j;
}
return Result;
//第二种方法可以使用位移操作
//逐个判断每位上的数字
// long long Temp = static_cast<long long>(n);
// if (Temp<0)
// {
// //处理补码的情况
// Temp = UINT_MAX + n + 1;
// }
// string Result("");
// while (Temp)
// {
// if (Temp&0x01)
// {
// Result += '1';
// }
// else
// {
// Result += '0';
// }
// Temp >>= 1;
// }
// //翻转字符串
// int i = 0;
// int j = Result.size() - 1;
// while (i<j)
// {
// swap(Result[i], Result[j]);
// ++i;
// --j;
// }
// return Result;
}
十进制转换为二进制
最新推荐文章于 2025-05-29 10:40:39 发布