简体   繁体   English

在 C 中将十进制转换为具有数十亿数字的二进制

[英]Convert decimal to binary with billions number in C

#include<stdio.h>    
#include<stdlib.h>  

int main() {
    long long *a, n, i;
    while (0 != 1) {
        printf("Enter the number to convert: ");
        scanf("%lli", &n);
        a = (int*) malloc(n * sizeof (int));
        printf("%p", a);
        for (i = 0; n > 0; i++) {
            a[i] = n % 2;
            n = n / 2;
        }
        printf("\nBinary of Given Number is=");
        for (i = i - 1; i >= 0; i--) {
            printf("%lli", a[i]);
        }
        __fpurge(stdin);
        getchar();
    }
}

I have this code, my teacher request input number 77777777777777777777777777777777777777777777 and convert to binary.我有这个代码,我的老师要求输入数字 77777777777777777777777777777777777777777777 并转换为二进制。 But program can't run with this number, it's too long.但是程序不能用这个数字运行,它太长了。 So anyone can help me, how to input billion number and program can run.所以任何人都可以帮助我,如何输入十亿数字和程序可以运行。

Since your input is too large for an int type you can use a string and manipulate it using the same algorithm.由于您的输入对于 int 类型来说太大了,您可以使用字符串并使用相同的算法对其进行操作。

#include <stdio.h>    
#include <stdlib.h>  
#include <string.h>
#include <stdbool.h>

bool isZero(const char *s, int len)
{
    for (int i = 0; i < len; ++i)
    {
        if (s[i] != '0')
        {
            return false;
        }
    }
    return true;
}

void div2(char *s, int len)
{
    int remainder = 0;
    for (int i = 0; i < len; ++i)
    {
        int digit = s[i] - '0' + remainder;
        remainder = 10 * (digit % 2);
        s[i] = '0' + (digit / 2);
    }
}

int main()
{
    char input[256] = "77777777777777777777777777777777777777777777";
    char bits[2048] = { 0 };

    int len = strlen(input);
    for (int i = 0; i < len; ++i)
    {
        if (input[i] < '0' || input[i] > '9')
        {
            printf("%c is not a numeric digit, exiting.\n", input[i]);
            return -1;
        }
    }

    int pos = 0;
    while (!isZero(input, len))
    {
        int digit = input[len - 1] - '0';
        bits[pos++] = '0' + (digit % 2);
        div2(input, len);
    }

    len = strlen(bits);
    while (len--)
    {
        putchar(bits[len]);
    }
    putchar('\n');

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM