二进制转换器不适用于大数字

时间:2013-01-31 05:41:13

标签: c binary type-conversion largenumber

我正在编写从整数转换为二进制表示的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;
}

2 个答案:

答案 0 :(得分:1)

您正在使用long long将二进制数表示为小数。在许多体系结构中,这导致最大值存储为2 ** 64-1 = 18446744073709551615。

如果输入十进制数,例如10000000,则不能将其表示为64位的十进制二进制数。

答案 1 :(得分:-2)

问题是试图将二进制数作为10的幂之和进行操作。直接操作二进制文件更有效。只需在10函数中将2更改为reverse_int

unsigned long long reverse_int(unsigned long long l) {
        unsigned long long reversed; 
        reversed = 0;
        while (l > 0) {
                reversed = reversed * 2 + (l%2);
                l = l / 2;
        }
        return reversed;
}

为了以二进制形式打印数字,写一个循环,按顺序测试每个位,使用模%或按位运算符,如&>>