<p><strong><span style="font-size:32px;">
编程实现,把十进制数(long型)分别以二进制和十六进制形式输出,不能使用printf系列库函数。</span></strong></p><p><strong><span style="font-size:32px;">这个用堆栈地方法很容易实现,但我试了下非堆栈法,我写的不太好,望指教。</span></strong></p><p>
</p>
<span style="font-size:24px;"><strong>#define _CRT_SECURE_NO_WARNINGS
/*将十进制转换为二进制和八进制和十六进制不使用库函数*/
#include <stdio.h>
#include <stdlib.h>
/*非堆栈写法*/
void main()
{
printf("请输入一个十进制数\n");
int num;
scanf("%d", &num);
int num2[100];//用于存放缓冲
int i = 0;
int count = 0;
while (num != 0)
{
num2[++i] = num % 2;//因为自加运算符的性质先应用再自加num[0]不存数
num /= 2;//将num变为原来的一半
}
count = i;
printf("二进制为:\n");
while (i)
{
printf("%d", num2[i]);
i--;
}
char numF[] = { "0123456789ABCDEF" };//构建顺序表
printf("\n输出16进制是:\n");
int temp = count % 4;//当最高位没有4个时处理
int temp1 = 0;//零时变量用于记录4位之和
if (temp > 0)//如果有四位则不执行这步
{
while (temp)
{
if (temp == 3)
temp1 = temp1 + num2[count--] * 4;//通过自减元算服,先应用后自减
if (temp == 2)
temp1 = temp1 + num2[count--] * 2;
if (temp == 1)
temp1 = temp1 + num2[count--] * 1;
temp--;
}
printf("%c", numF[temp1]);
}
temp = 8;
temp1 = 0;
while (count)
{
temp1 = temp1 + num2[count--] * temp;
temp /= 2;
if (temp == 0)
{
temp = 8;
printf("%c", numF[temp1]);
temp1 = 0;
}
}
system("pause");
}</strong></span>
<p><strong><span style="font-size:32px;">附上尹成大大的代码。</span></strong></p><div><strong><span style="font-size:32px;"></span></strong><pre name="code" class="cpp">#include <stdio.h>
void PrintBin(long num)
{
char buf[256] = { 0 };
//移位判断每一位
for (int i=0,j = sizeof(long)* 8 - 1; j >= 0; j--, i++)
{
if ((num >> j) & 1)
{
buf[i] = '1';
}
else
{
buf[i] = '0';
}
}
puts(buf);
}
void PrintHex(long num)
{
char HexChar[] = { "0123456789ABCDEF" };
char buf[256] = { 0 };
//移位判断每四位
for (int i=0,j = sizeof(long)* 8 - 4; j >= 0; j -= 4, i++)
{
int index = (num >> j) & 0xF;
buf[i] = HexChar[index];//取四位对应的十六进制字符
}
puts(buf);
}
int main()
{
PrintBin(1555);
PrintHex(1555);
return 0;
}