×

# reversing array for conversion to binary number

 0 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 #include 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 0★techbiz 1●1●1 accept rate: 0% 3★kuruma 17.7k●72●143●209

 0 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 #include 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 answered 23 Jun '13, 14:53 3★kuruma 17.7k●72●143●209 accept rate: 8%
 0 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 #include #include 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
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• 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,014 times

last updated: 23 Jun '13, 15:14