reversing array for conversion to binary number

conversion
reverse

#1

I’m looking to perform the decimal to binary conversion…how do I reverse the binary code stored in str*, 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*=c; // ***** the binary value is stored here

           printf("%d", str*);
           a=a/2;
           i++;
        }
   }

}

#2

Hello,

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* = 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!

Best regards,

Bruno


#3

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*=a%2; // ***** the binary value is stored here
         a /= 2;
     }
     
     for(i=0;i<n;i++)
        printf("%d",str*);
     printf("

");
return 0;
}

link