-3

I was practicing basic programs of C and tried to do a binary to decimal conversion.

Below is the code I tried but it did not produce correct results. I couldn't understand where my logic goes wrong.

/*     binary to decimal     */
#include<stdio.h>
int main()
{
    int a,i,p,sum=0;
    printf("enter binary number\n");
    scanf("%u",&a);
    for(i = 0 ; i < 5; i++)  /* Taking only 5 digits in binary */
    {
        if((a  & 1<<i)) 
        { 
            p = 1<<i;        
            sum = sum +p;
        }
    }

    printf("%d\n",sum);
    return 0;
}

I entered 1001 and was expecting 9 to be the output, but output was 1001?

phuclv
  • 37,963
  • 15
  • 156
  • 475
mrigendra
  • 1,472
  • 3
  • 19
  • 33

6 Answers6

1

scanf("%u",&a); will read a decimal number. Therefore when you enter 1001 it will be 0011 1110 1001 in binary and after you convert this number back to decimal it becomes 100110. You should read it as a string to preserve the binary form

And then the code you wrote only checks the lower 5 bits of the input value. If you enter 1001 it will output 9 as "expected" because the lower bits of 1001 is 01001 which is accidentally the same for 9. The output is not 1001 as you described. That means the code above is not the original code you ran. If you enter another number the result will be different. For example entering 36 will print 4 on the output

phuclv
  • 37,963
  • 15
  • 156
  • 475
0

Reason is very simple, variable 'a' is of type int hence when you provide the input as 1001 it becomes a integer of 1001 not a binary for the compiler, so you will not get the proper result, don't use shift operator, try some thing similar as suggested by others

Kumareshan
  • 1,311
  • 8
  • 8
0

This should help you:

#include<stdio.h>
 int main()
 {
   int a,i,p,sum=0;
   int temp;

   printf("enter binary number\n");
   scanf("%d",&a);

   for(i = 0 ; i<5; i++)  /* Taking only 5 digits in binary */
   {
    temp=a % 10;
     a = a/10;

     p = temp<<i;
     sum = sum +p;
   }

  printf("%d\n",sum);
  return 0;
 }
Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
  • 2
    @Jongware WOW! So now I should explain step by step to the OP. Dear Sir if he can write that much code, I don't need to feed him explainations as well. – Umer Farooq Oct 20 '13 at 20:01
  • No, you just *presented* your own code. Part of the learning experience is *teaching*. The OP was wondering why his (reasonable) attempt failed. Saying "here, simply use this" is not "the answer". The other answers *do* address the underlying issue, whereas yours doesn't imply *you* understood what was going on. – Jongware Oct 20 '13 at 20:14
0

You would do better to take the input as a string, and starting from the end of that string add the place values for the 1 digits.

%u interprets a decimal string as an integer, you are then trying to interpret the decimal representation of the resultant integer value as binary. Not only is that confusing and somewhat irrational, it will limit you to 10 binary digits.

Consider this:

/*     binary to integer     */
#include <stdio.h>
#include <string.h>

int main()
{
    int pv = 1 ;
    int value = 0 ;
    char bin[33] ;

    printf("Enter binary number: ");
    scanf("%32s", bin ) ;

    for( int i = strlen( bin ) - 1; i >= 0; i-- )
    {
         if( bin[i] == '1' )
         {
             value += pv ;
         }

         pv *= 2 ;
    }

    printf( "%d\n", value ) ;

    return 0 ;
}

Note also that what is happening here is not a conversion to decimal, but rather conversion to integer. All values are stored internally in binary, it is only decimal if you choose to output a decimal string representation of the integer value.

A potentially more efficient version of the above that exploits the internal binary representation of integers is:

/*     binary to integer     */
#include <stdio.h>
#include <string.h>

int main()
{
    int pv = 1 ;
    int value = 0 ;
    char bin[33] ;

    printf("Enter binary number: ");
    scanf("%32s", bin ) ;

    for( int i = strlen( bin ) - 1; i >= 0; i-- )
    {
         if( bin[i] == '1' )
         {
             value |= pv ;
         }

         pv <<= 1 ; ;
    }

    printf( "%d\n", value ) ;

    return 0 ;
}
Clifford
  • 88,407
  • 13
  • 85
  • 165
-1

These lines are wrong (I think..):

p = 1<<i;
sum = sum +p;

In order to comput the decimal value you have to do this:

p= pow(2,i);
sum = sum+p;

You need to raise 2 to the power i.
See this link for a good example code: http://www.daniweb.com/software-development/c/threads/307756/binary-to-decimal-conversion-in-c

RRR
  • 3,937
  • 13
  • 51
  • 75
-1

This code can be used in C++:

string str = "1001";
int temp = 0;
for(int c=0;c<str.length();c++){

      int v = atoi( str.substr(c,1).c_str() );
      temp=temp+(v*(pow (2, str.length()-c-1)));

}

cout << temp;
Jonathan Gurebo
  • 1,089
  • 1
  • 11
  • 21