The Way to Programming
The Way to Programming
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?
#includeint 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; }
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; }
Sign in to your account