I’m looking to perform the decimal to binary conversion…how do I reverse the binary code stored in str[i], marked in asterisk so that I get the correct output ??
#include <stdio.h>
#include <string.h>
void main()
{
int a, b, c, i;
int str[10];
printf("Enter an integer of your choice : ");
scanf("%d", &a);
b=a;
while (a!=0)
{
for (i=0;a>i;i++)
{
c=a%2;
str[i]=c; // ***** the binary value is stored here
printf("%d", str[i]);
a=a/2;
i++;
}
}
}
The trick is that after you have stored all the remainders on the array, you just need to use printf inside a loop and print the contents of the array from the highest index, to the lowest.
In my code, the highest index is i-1, where i is a counter for the number of digits on the binary representation of the number:
#include <string.h>
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
int str[100];
int i = 0; /* stores number of digits on binary representation */
while(n>0)
{
str[i] = n%2;
n/=2;
i++;
}
int j;
for(j=i-1; j>=0;j--)
printf("%d",str[j]);
return 0;
}
If you need any further help, please, don’t hesitate to ask!
hey there, I have changed some part of your program, it looks easy now and is able to print binary of any number u want to input…
#include <stdio.h>
#include <string.h>
#include<math.h>
int main()
{
int a,i;
scanf("%d", &a);
int n = (int)(ceil(log2(a+1)));
int str[n];
printf("Binary of %d is : ", a);
for(i=n-1;i>=0;i--) {
str[i]=a%2; // ***** the binary value is stored here
a /= 2;
}
for(i=0;i<n;i++)
printf("%d",str[i]);
printf("\n");
return 0;
}