Write a program that reads a decimal value and converts it to binary using binary operators.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
void main ()
{
int M, u;
int counter=0;
printf("Enter an decimal integer: ");
scanf("%d", &M);
printf("In binary : ");
/* we counts least significant bit */
u=M;
while ((u&1)!=1)
{
u=u>>1;
counter++;
}
/* Necessary to keep M value for the M%2 test */
u=M;
/* Reading from left to right : we place ourselves on the 1st
* non zero most significant bit */
while (u>0) u=u<<1;
/*Now we show the bits from left to right */
while (u!=0)
{
if (u<0)
printf("%c",'1');
else
printf("%c",'0');
u=u<<1;
}
/* In the case where M is even, you have to take into account its
* least significant bits of zeros */
if (M%2==0)
while (counter !=0)
{
printf("%c",'0');
counter--;
}
putchar('\n');
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Articulation points cut bridges and cut edges