char* numberToBinaryString(int n)
{
bool isLowZero = n < 0;
n = abs(n);
char* str = new char[33];
memset(str, 0, 33);
unsigned short idx = 0;
//逆序的方便后面负数原码转补码的时候+1
while (n != 0)
{
str[idx] = 0x30 + n % 2;
idx++;
n /= 2;
}
size_t len = strlen(str);
//补全
size_t d = 31 - len;
for (size_t i = 0; i < d; i++)
str[len + i] = 0x30;
len += d;
//如果是负数,则用补码表示.负数的补码等于原码取反加1,符号位不变
if (isLowZero)
{
//取反
for (unsigned short i = 0; i < len; i++)
{
if (str[i] == 0x30)
str[i] += 1;
else
str[i] -= 1;
}
//加1
for (unsigned short i = 0; i < len; i++)
{
if (str[i] == 0x30)
{
str[i] = 0x31;
break;
}
else
{
str[i] = 0x30;
//最后一位还是0x31, 则需要进位
if (i == (len - 1))
{
str[len] = 0x31;
len++;
}
}
}
//增加符号位
str[len] = 0x31;
len++;
}
//翻转
for (unsigned short i = 0; i < len / 2; i++)
{
char t = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = t;
}
cout << str << endl;
return str;
}
将一个int型十进制数字转成二进制数字字符串
最新推荐文章于 2022-07-29 21:33:41 发布