Reputation: 25
I am trying to create a program that converts decimal to binary and prints 0b before the binary.
I need the program to print 0b0 if 0 is the input, and 0b11101 when input is 29. I can seem to do one, but not the other, and when I fix that bug, the other stops working
Where am I going wrong ?
#include <stdio.h>
int main()
{
int n,i = 0,j=0,k;
scanf("%d",&n);
int bin[100];
k=n;
//printf("n is %d \n",n);
while(n!=0)
{
//printf("n is %d :\n",n);
bin[i]= n%2;
//printf ("n/2 is %d\n",n%2);
n=(n-n%2)/2;
i++;
//printf("i is %d\n",i);
}
printf("0b");
//if (n='0')
//{
// printf("0");
//}
//else
//{
for (j=i;j>0;j--)
{
//printf("\n j is,%d and there ,is %d\n",j,bin[(j-1)]);
printf("%d",bin[(j-1)]);
}
//}
}
Upvotes: 2
Views: 87
Reputation: 1223
A naive and more portable implementation of a decimal to binary conversion function ...
#include <limits.h>
void print_binary(unsigned x){
unsigned n=UINT_MAX;
n = ~(n >> 1);
while (n){
if (n & x)
putchar('1');
else
putchar('0');
n = n >> 1;
}
putchar('\n');
}
Upvotes: 0
Reputation: 153507
0 does not need to be treated as a special case. Simply fix: use a do
loop rather than while ()
.
#include <stdio.h>
int main() {
int n,i = 0,j=0,k;
scanf("%d",&n);
int bin[100];
// k=n; // not needed
// while(n!=0) {
do {
bin[i]= n%2;
// Another simplification
// n=(n-n%2)/2;
n /= 2;
i++;
} while (n);
printf("0b");
for (j=i;j>0;j--) {
printf("%d",bin[(j-1)]);
}
}
Other coding needed to handle n<0
.
Upvotes: 1
Reputation: 3441
#include <stdio.h>
int main()
{
int n,i = 0,j=0,k;
scanf("%d",&n);
int bin[100];
k=n;
while(n!=0)
{
bin[i]= n%2;
n=(n-n%2)/2;
i++;
}
printf("0b");
if (k==0)
{
printf("0");
}
else
{
for (j=i-1;j>=0;j--)
{
printf("%d",bin[(j-1)]);
}
}
}
Upvotes: 0