• Converting base_10 number to base_2 in C Programming

    Ganesh Member

    I have a problem with my code. If I enter a big integer like 18,446,744,073….. it gives back an answer as 1111111111111111111111111111111.
    Do I need to use unsigned long long int instead of long int? If so what needs to be changed in my program?

    #include 
    
    int main(void)
    {
       long int dec, num;
       int store[100], i=1,j;
    
       printf("Enter a base_10 number from 0 to 18,446,744,073,709,551,615: ");
    
       scanf("%ld",&dec);
    
       num = dec;
    
       while(num!=0)
       {
          store[i++]=num%2;
          num=num/2;
       }
    
       printf("The binary value for %d is: ",dec);
    
       for(j=i-1;j>0;j--)
       {
         printf("%d",store[j]);
       }
    
       printf("\n");
    
       return 0;
    }
    
  • Adan Member

    Your algorithm is correct… I changed it a bit in order to work with large numbers. I think your error is in variable maximum size

    This works at least in Linux and if you use it you have to link the code with the crypto library (by adding -lssl or -lcrypto to the libraries maybe not sure how it works on windows)
    In Windows all you have to do to work with these libraries is to install OpenSSL i believe

    https://www.openssl.org/related/binaries.html

    (Now your limit is not 18,446,744,073,709,551,615)

    #include 
    #include 
    #include 
    
    #define MAXNUM 1000
    
    int main(void)
    {
       char dec[MAXNUM];
       int i = 0;
    
       printf("Enter a base_10 number from 0 to 18,446,744,073,709,551,615: ");
    
       scanf("%s", dec);
    
       BIGNUM * numero = BN_new();
       BIGNUM * d = BN_new();
       BIGNUM * rem = BN_new();
       BN_add_word(d, 2);
       BN_asc2bn(&numero, dec);
    
       unsigned int store[BN_num_bits(numero)];
       memset(store, 0, BN_num_bits(numero));
    
       BN_CTX * ctx = BN_CTX_new();
       while(!BN_is_zero(numero)) {
          BN_zero(rem);
          BN_div(numero, rem, numero, d, ctx);
          store[i++] = (BN_get_word(rem));
       }
    
       printf("The binary value for %s is: ", dec);
       int j;
       for(j = i - 1; j >= 0; j--) {
          printf("%u", store[j]);
       }
    
       printf("\n");
    
       return 0;
    }
    
  • Amit Member

    You need to declare it as unsigned long long.
    long long signed int: 2^63-1
    unsigned long long int: 2^64-1

Viewing 2 reply threads
  • You must be logged in to reply to this topic.
en_USEnglish