我正在编写从整数转换为其二进制表示形式的 C 代码,反转二进制然后再转换回整数。它运行良好,但我需要它来处理高达 10^9 的输入值。现在,它似乎会因任何大于 10^7 的东西而中断。我的意思是我输入一个数字,例如 10000000,然后输出 17967657062982931584 作为二进制表示(尽管对于较小的整数是准确的)。此外,我不确定我的 int_to_binary 是唯一遇到此问题的函数,或者其他函数是否也需要针对大输入进行优化。有什么想法我哪里出错了吗?谢谢你。
#include <stdio.h>
#include <string.h>
unsigned long long int_to_binary(unsigned long long k) {
if (k == 0) return 0;
if (k == 1) return 1;
return (k % 2) + 10 * int_to_binary(k/2);
}
unsigned long long reverse_int(unsigned long long l) {
unsigned long long reversed;
reversed = 0;
while (l > 0) {
reversed = reversed * 10 + (l%10);
l = l / 10;
}
return reversed;
}
unsigned long long binary_to_int(unsigned long long k) {
char binaryString[80];
snprintf(binaryString, 4, "%llu", k);
unsigned long long decimal = 0;
int length = strlen(binaryString);
int i = 0;
while(i < length) {
decimal = (decimal << 1) + (binaryString[i] - 0x30);
i++;
}
return decimal;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered %d\n", number);
unsigned long long b = int_to_binary(number);
printf("In Binary, this is %llu\n", b);
unsigned long long c = reverse_int(b);
printf("When we reverse it, it looks like this: %llu\n", c);
unsigned long long d = binary_to_int(c);
printf("And when we convert that back to an int, it looks like this: %llu\n", d);
return 0;
}