【发布时间】:2015-05-18 00:32:43
【问题描述】:
我正在编写一个将整数转换为 32 位二进制的程序。问题出在输出上——它倒退了。
#include <stdio.h>
int main() {
long number, binary, num2;
printf("Enter an integer: ");
scanf("%ld", &number);
for (num2 = (number * 2) / 2; num2 > 0; num2 /= 2) {
binary = num2 % 2;
printf("%ld", binary);
}
putchar('\n');
return 0;
}
所以如果我输入“6”,它会显示为 011,它必须是 110
另外,我如何输出其余的“0”?所以在这种情况下,整个输出将是:
00000000 00000000 00000000 00000110
【问题讨论】:
-
number 是一个整数,所以 (number * 2) / 2 等于 number ! (假设没有溢出,并且编译器不会优化它。
-
另外,我在搜索引擎中输入了你的问题标题,不出所料,点击率很高!
-
@MitchWheat 我敢打赌它们中的大多数会由于整数溢出而导致未定义的行为
标签: c binary converters