You are not logged in. Please login at www.codechef.com to post your questions!

×

reversing array for conversion to binary number

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++;
        }
   }

}

asked 23 Jun '13, 14:37

techbiz's gravatar image

0★techbiz
111
accept rate: 0%

edited 23 Jun '13, 14:42

kuruma's gravatar image

3★kuruma
17.7k72143209


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[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!

Best regards,

Bruno

link

answered 23 Jun '13, 14:53

kuruma's gravatar image

3★kuruma
17.7k72143209
accept rate: 8%

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;
}

link

link

answered 23 Jun '13, 15:14

devanshug's gravatar image

4★devanshug
2.7k111927
accept rate: 13%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×27
×17

question asked: 23 Jun '13, 14:37

question was seen: 1,002 times

last updated: 23 Jun '13, 15:14