954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

problem to convert binary numbers to decimal. Someone HELP

I started to program on C++ on converting 8bit binary to its decimal requested for my school project. But i have problem to proceed further as i am lost on what to add on next. Can someone help me to add on to my program to allow it to work.. ThX for your help.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>

int main()
{
    char binaryinput[8];
    char binaryoutput[8];
    char response;
    int i;
    int result = 0;
    
    do
    {

        
    printf("\t4: 8-bit Binary to Decimal Conversion\n");//binarytodecimal function call
    printf("\t=====================================\n\n");
    printf("\tPlease enter an 8-bit binary bits:");
    
    for(i=7; i<8; i--)
    {
        binaryinput[i] = getche();
    }
    
    for(i=0; i<8; i++)
    {
       if(binaryinput[0] == '1')
       {
           result = binaryinput[i] * pow(2,0);
           
       }  
       else if(binaryinput[0] == '0')
       {
           
       }    
       
         printf("\n\tThe binary number %s has been converted to %d decimal\n\n",i ,result);
       
         response = getch();  
    }
 
       while (( response == 'y') || ( response == 'Y'));  
         
    system("pause");
    return 0;
}
imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

It looks like you're mixing solutions, and you added too much fluffy code without getting a solid solution first.

>char binaryinput[8];
If you're going to print binaryinput as a string later, you need to leave room for a null character at the end.

>printf("\tPlease enter an 8-bit binary bits:");
If you don't print a newline, be sure to call fflush so that the output is guaranteed to be shown before blocking for input. You're not likely to have a problem on Windows systems, but this is a portability concern.

>for(i=7; i<8; i--)
You really only need to loop from 0 to 8. No tricks needed, and this loop is severely broken.

>if(binaryinput[0] == '1')
Obviously you'll need to compare against binaryinput[i] rather than binaryinput[0] , otherwise the loop won't work as intended.

result = binaryinput[i] * pow(2,0);


is pointless as written, but I suspect what you wanted was to add the result of pow to result :

result += (int)pow ( 2, 7 - i );

The cast to int will silence a warning about double truncation, and 7-i gets you the right exponent from the loop index.>else if(binaryinput[0] == '0')
This comparison isn't necessary as work only needs to be done for set bits.

All of the problems are pretty simple, and it looks like you have a fairly good idea of how the solution should work, so I'll give you my version of the code to compare and contrast:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define BASE 2
#define BITS 8
#define HIBIT 7
#define LOBIT 0

static const char *prompt_msg = 
  "Please enter an %d-bit binary number: ";
static const char *result_msg = 
  "%s binary has been converted to %d decimal\n";

int main ( void )
{
  char binaryinput[BITS + 1] = {0};
  int result = 0;
  int i;

  printf ( prompt_msg, BITS );
  fflush ( stdout );

  for ( i = LOBIT; i < BITS; i++ )
    binaryinput[i] = (char)getchar();

  for ( i = LOBIT; i < BITS; i++ ) {
    if ( binaryinput[i] != '0' )
      result += (int)pow ( BASE, HIBIT - i );
  }

  printf ( result_msg, binaryinput, result );

  return 0;
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

I have tried to rewrite the codes with reference with your code. But somehow it does not worked. what's the problem? N thx for helping me.. prehaps could u write some block comments to allow me understand better of what u r writing because i'm still quite new in C++ programming..

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>

int main()
{
    char binaryinput[9] = {0};
    char response;
    int i;
    int result = 0;
        
    printf("\t4: 8-bit Binary to Decimal Conversion\n");//binarytodecimal function call
    printf("\t=====================================\n\n");
    printf("\tPlease enter an 8-bit binary bits: ");
    
    do
    {
      for(i=0; i<8; i++)
       {
           binaryinput[i] = (char)getche();
       }  
            
      for(i=0; i<8; i++)
    {
       if(binaryinput[i] != '1')
       {
           result += (int)pow (2, 7 - i);
       }   
    }        
         printf("\n\tThe binary number %s has been converted to %d decimal\n\n",i ,result);
         printf("\tTry for another conversion? ");
       
         response = getch();    
    } 
      while (( response == 'y') || ( response == 'Y'));  
         
    system("pause");
    return 0;
}
imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

even if i modify the code form above to
if(binaryinput[i] != '0') the program still doesn't work when it run.

imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

hint: on this line
printf("\n\tThe binary number %s has been converted to %d decimal\n\n",i ,result); the variable i is not a null terminated string.

Also, try fgets(reference here - ignore that it's a C++ site)for your input it's much cleaner (and standard).

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

Also don't use conio.h . It is not a part of the standard C library. I guess you're compiler is quite outdated. I recommend Code::Blocks

xavier666
Junior Poster
173 posts since Sep 2009
Reputation Points: 71
Solved Threads: 10
 

Anyone know how to write the code from the existing format above that could display the working at the same time after the input of the binary number when running the application.

EG:
8-bit Binary to Decimal Conversion
========================

Please enter binary bits: 10101010

128 + 0 + 32 + 0 + 8 + 0 + 2 + 0 = 170

The binary number 10101010 has been converted to 170 decimal

Try for another conversion?

imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

printf (int)pow (2, 7 - i) with a plus sign after it unless it's the last bit (no extra + at the end). If you don't put a '\n' into your printf it will all go on one line.
Did the other corrections work?

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 
printf (int)pow (2, 7 - i) with a plus sign after it unless it's the last bit (no extra + at the end). If you don't put a '\n' into your printf it will all go on one line. Did the other corrections work?

what do u mean by "with a plus sign after it unless it's the last bit (no extra + at the end)"? And the corrections has allow it to work but i still do not understand the fget function!

imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

If you're printing a chain of additions out, each will have printf("%d + ",powexpression) except for the last which will have printf("%d,pow expression) so you'd have "128 +" (next loop) "0 +" (next loop) + ...+"0"

fgets just takes your array, binaryinput, the size of your array, 9 (as Narue pointed out), and stdin (as it can be used with other streams.
besides standard input). It's safer in that it takes in only your 8 characters and null terminates the string. getche is also specific to the conio library and is as xavier pointed out non-standard (as is system("pause") but we'll save that for another time.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

If you're printing a chain of additions out, each will have printf("%d + ",powexpression) except for the last which will have printf("%d,pow expression) so you'd have "128 +" (next loop) "0 +" (next loop) + ...+"0"

fgets just takes your array, binaryinput, the size of your array, 9 (as Narue pointed out), and stdin (as it can be used with other streams. besides standard input). It's safer in that it takes in only your 8 characters and null terminates the string. getche is also specific to the conio library and is as xavier pointed out non-standard (as is system("pause") but we'll save that for another time.


i still can't figure out where to place this expression "except for the last which will have printf("%d,pow expression)". Is it in the for loop.

imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

i tried to force only "1" and "0" binary numbers to input into binaryinput so that it only accepts 1 and 0 only but it does not work.. someone help me to improve on my codes.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>

int main()
{  
    char binaryinput[8];
    char response;
    int i;
    int result = 0;

    printf("\t4: 8-bit Binary to Decimal Conversion\n");//binarytodecimal function call
    printf("\t=====================================\n\n");
    printf("\tPlease enter an 8-bit binary bits: ");
   
    do
    {
      for(i=0; i<8; i++)
       {
           binaryinput[i] = getche();//user input stored into binaryinput
       }  
       
       printf("\n\n\t");
            
      if( binaryinput[i] == "0" &&  binaryinput[i] "1")
      {
      for(i=0; i<8; i++)
    {
       if(binaryinput[i] != '0')
       {
           result += (int)pow (2, 7 - i);
       }   
    }        
       
      for(i=0; i<7; i++)
    {
       if(binaryinput[i] != '0')
       {
           printf("%d + ",(int)pow (2, 7 - i));
       }   
    }        
         printf("%d ", (int)pow (2, 7 - binaryinput[7]));
         printf("= %d",result);
     }    
         printf("\n\n\tThe binary number %s has been converted to %d decimal\n\n",binaryinput ,result);
         printf("\tTry for another conversion? ");
       
         response = getch();    
    } 
      while (( response == 'y') || ( response == 'Y'));  
         
    system("pause");
    return 0;
}
imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

It looks like you're mixing solutions, and you added too much fluffy code without getting a solid solution first.

>char binaryinput[8]; If you're going to print binaryinput as a string later, you need to leave room for a null character at the end.

>printf("\tPlease enter an 8-bit binary bits:"); If you don't print a newline, be sure to call fflush so that the output is guaranteed to be shown before blocking for input. You're not likely to have a problem on Windows systems, but this is a portability concern.

>for(i=7; i<8; i--) You really only need to loop from 0 to 8. No tricks needed, and this loop is severely broken.

>if(binaryinput[0] == '1') Obviously you'll need to compare against binaryinput[i] rather than binaryinput[0] , otherwise the loop won't work as intended.

result = binaryinput[i] * pow(2,0);

is pointless as written, but I suspect what you wanted was to add the result of pow to result :

result += (int)pow ( 2, 7 - i );

The cast to int will silence a warning about double truncation, and 7-i gets you the right exponent from the loop index.>else if(binaryinput[0] == '0') This comparison isn't necessary as work only needs to be done for set bits.

All of the problems are pretty simple, and it looks like you have a fairly good idea of how the solution should work, so I'll give you my version of the code to compare and contrast:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define BASE 2
#define BITS 8
#define HIBIT 7
#define LOBIT 0

static const char *prompt_msg = 
  "Please enter an %d-bit binary number: ";
static const char *result_msg = 
  "%s binary has been converted to %d decimal\n";

int main ( void )
{
  char binaryinput[BITS + 1] = {0};
  int result = 0;
  int i;

  printf ( prompt_msg, BITS );
  fflush ( stdout );

  for ( i = LOBIT; i < BITS; i++ )
    binaryinput[i] = (char)getchar();

  for ( i = LOBIT; i < BITS; i++ ) {
    if ( binaryinput[i] != '0' )
      result += (int)pow ( BASE, HIBIT - i );
  }

  printf ( result_msg, binaryinput, result );

  return 0;
}


i tried to force only "1" and "0" into the binaryinput so that it onlt accepts 1 and 0 only but it does not work.. Can you help me to improve on my codes.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>

int main()
{ 
char binaryinput[8];
char response;
int i;
int result = 0;

printf("\t4: 8-bit Binary to Decimal Conversion\n");//binarytodecimal function call
printf("\t=====================================\n\n");
printf("\tPlease enter an 8-bit binary bits: ");

do
{
for(i=0; i<8; i++)
{
= getche();//user input stored into binaryinput
} 

printf("\n\n\t");

if( binaryinput[i] == "0" && binaryinput[i] "1")
{
for(i=0; i<8; i++)
{
if(binaryinput[i] != '0')
{
result += (int)pow (2, 7 - i);
} 
} 

for(i=0; i<7; i++)
{
if(binaryinput[i] != '0')
{
printf("%d + ",(int)pow (2, 7 - i));
} 
} 
printf("%d ", (int)pow (2, 7 - binaryinput[7]));
printf("= %d",result);
} 
printf("\n\n\tThe binary number %s has been converted to %d decimal\n\n",binaryinput ,result);
printf("\tTry for another conversion? ");

response = getch(); 
} 
while (( response == 'y') || ( response == 'Y')); 

system("pause");
return 0;
}
imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

You're using getche for input, so you could interactively force either '0' or '1' and save yourself validation efforts after the fact:

#include <stdio.h>
#include <math.h>
#include <conio.h>

int main ( void )
{
  char binaryinput[9] = {0};
  int result = 0;
  int i;

  printf ( "Please enter an 8-bit binary number: " );
  fflush ( stdout );

  for ( i = 0; i < 8; )
  {
    /* Don't echo until we know it's a valid character */
    int ch = getch();

    if ( ch == '0' || ch == '1' )
    {
      binaryinput[i++] = (char)ch;

      /* Echo the character manually */
      putch ( ch );
    }
  }

  for ( i = 0; i < 8; i++ )
  {
    if ( binaryinput[i] != '0' )
      result += (int)pow ( 2, 7 - i );
  }

  printf ( "\n%s binary is %d decimal\n", binaryinput, result );

  return 0;
}

Another option is to allow the user to enter the string completely, then validate it. This would be your best option if you used standard input rather than the non-standard conio library:

#include <stdio.h>
#include <math.h>
#include <conio.h>

int main ( void )
{
  char binaryinput[9] = {0};
  int result = 0;
  int i;

  printf ( "Please enter an 8-bit binary number: " );
  fflush ( stdout );

  for ( ; ; )
  {
    /* Get a valid binary string */
    for ( i = 0; i < 8; i++ )
      binaryinput[i] = getche();

    /* Validate input */
    for ( i = 0; i < 8; i++ )
    {
      if ( binaryinput[i] != '0' && binaryinput[i] != '1' )
        break;
    }

    /* If we validated to the end, the string is clean */
    if ( i == 8 )
      break;

    /* Otherwise make the user try again */
    fputs ( "\nInvalid binary string. Please try again: ", stdout );
    fflush ( stdout );
  }

  for ( i = 0; i < 8; i++ )
  {
    if ( binaryinput[i] != '0' )
      result += (int)pow ( 2, 7 - i );
  }

  printf ( "\n%s binary is %d decimal\n", binaryinput, result );

  return 0;
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

If you're printing a chain of additions out, each will have printf("%d + ",powexpression) except for the last which will have printf("%d,pow expression) so you'd have "128 +" (next loop) "0 +" (next loop) + ...+"0"

fgets just takes your array, binaryinput, the size of your array, 9 (as Narue pointed out), and stdin (as it can be used with other streams. besides standard input). It's safer in that it takes in only your 8 characters and null terminates the string. getche is also specific to the conio library and is as xavier pointed out non-standard (as is system("pause") but we'll save that for another time.

Anyway what is the powerexpression?

imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

Sorry, that was my abbreviation (it might have been faster just to write it out hehe) for (int)pow (2, 7 - i) .

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 
Sorry, that was my abbreviation (it might have been faster just to write it out hehe) for (int)pow (2, 7 - i) .


but this expression does not show the Zeros of the binary zero. It just loop through ignoring the presence of a zero binary. Or something is wrong with my codes?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>

int main()
{  
    char binaryinput[9];
    char response;
    int i;
    int result = 0;

    printf("\t4: 8-bit Binary to Decimal Conversion\n");//binarytodecimal function call
    printf("\t=====================================\n\n");
    printf("\tPlease enter an 8-bit binary bits: ");
   
    do
    {
      for(i=0; i<8; i++)
       {
          binaryinput[i] = getche();//user input stored into binaryinput
       }  
       
       printf("\n\n\t");
            
      
      for(i=0; i<8; i++)
    {
       if(binaryinput[i] != '0')//might have to change
       {
           result += (int)pow (2, 7 - i);
       }   
    }        
       
      for(i=0; i<8; i++)
    {
       if(binaryinput[i] != '0')
       {   
           printf("%d + ", (int)pow (2, 7 - i));
       }   
    }    
         printf("%d ", (int)pow (2, 7 - binaryinput[7]));
         printf("= %d",result);
         
         printf("\n\n\tThe binary number %s has been converted to %d decimal\n\n",binaryinput ,result);
         printf("\tTry for another conversion? ");
       
         response = getch();    
    } 
      while (( response == 'y') || ( response == 'Y'));  
         
    system("pause");
    return 0;
}
imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 
if(binaryinput[i] != '0')
{
       printf("%d + ", (int)pow (2, 7 - i));
} 
else
      printf("0+ ");  //this assumes you've screened your string to make 
                            //sure that there are no other digits
                            //which can be done when you are stepping through
                            //to calculate the result (e.g.   binaryinput[i] !='0' && 
                             //binaryinput[i] !='1'  then break out of the loop

And PLEASE use code tags[code] //your code here [ /code] (no space before /)

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 
And PLEASE use code tags [code] //your code here [ /code] (no space before /)

If you want to show newbies how to use code-tags, you can use[noparse] tags.
If I type [noparse][code] // code here [/code][/noparse] it'll show as: [code] // code here [/code] :)

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 
if(binaryinput[i] != '0')
{
       printf("%d + ", (int)pow (2, 7 - i));
} 
else
      printf("0+ ");  //this assumes you've screened your string to make 
                            //sure that there are no other digits
                            //which can be done when you are stepping through
                            //to calculate the result (e.g.   binaryinput[i] !='0' && 
                             //binaryinput[i] !='1'  then break out of the loop

And PLEASE use code tags[code] //your code here [ /code] (no space before /)

Then how to handle with the last loop of the incrementation where there should be no plus sign appearing at he end of the loop?

imso
Junior Poster in Training
60 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You