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;
}

Recommended Answers

All 27 Replies

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 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;
}

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

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).

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

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?

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?

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!

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.

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.

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;
}

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;
}

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;
}

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?

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

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;
}
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 //your code here

And PLEASE use code tags

//your code here [ /code]  (no space before /)[/QUOTE] 

If you want to show newbies how to use code-tags, you can use [noparse][noparse][/noparse] tags. 
If I type [noparse][noparse]
[code]
 // code here

[/noparse][/noparse] it'll show as: [code] // code here [/code] :)

commented: Thanks! +1

start quote:

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 //your code here

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?

Either run your code from 0 to i<7 and afterwords put another if statement for the i = 7 case

for(i=0; i<7; i++)
    {
       if(binaryinput[i] != '0')
       {   
           printf("%d + ", (int)pow (2, 7 - i));
       }
       else
             printf("0 + ");
   
    }    
     if(binaryinput[7] == '1')
            printf("1 \n");
     else
            printf("0 \n");

You could also nest an if statement inside your other if

for(i=0; i<8; i++)
 {
       if(binaryinput[i] != '0')
       {   
           printf("%d ", (int)pow (2, 7 - i));
       }
        else
                printf("0 ");
      
     //new if statment
      if (i !=7)
           printf("+ ");
}

Either run your code from 0 to i<7 and afterwords put another if statement for the i = 7 case

for(i=0; i<7; i++)
    {
       if(binaryinput[i] != '0')
       {   
           printf("%d + ", (int)pow (2, 7 - i));
       }
       else
             printf("0 + ");
   
    }    
     if(binaryinput[7] == '1')
            printf("1 \n");
     else
            printf("0 \n");

You could also nest an if statement inside your other if

for(i=0; i<8; i++)
 {
       if(binaryinput[i] != '0')
       {   
           printf("%d ", (int)pow (2, 7 - i));
       }
        else
                printf("0 ");
      
     //new if statment
      if (i !=7)
           printf("+ ");
}

thanksf for your help.. By the way how come my output binay how there is some funny attachment at he back of my output code like - '''

>By the way how come my output binay how there is some
>funny attachment at he back of my output code like - '''

Probably because you didn't terminate the binaryinput array with the '\0' character. I do believe this was the very first thing I mentioned in this thread.

>By the way how come my output binay how there is some
>funny attachment at he back of my output code like - '''

Probably because you didn't terminate the binaryinput array with the '\0' character. I do believe this was the very first thing I mentioned in this thread.

Then how should i terminate the \0 NULL at he back of my binaryinput?

...

Well, you could look at the definition of binaryinput in any of the complete examples I gave you. Or you could do binaryinput[8] = '\0' anywhere between defining binaryinput and printing it (assuming you properly sized the array to 9 rather than 8).

...

Well, you could look at the definition of binaryinput in any of the complete examples I gave you. Or you could do binaryinput[8] = '\0' anywhere between defining binaryinput and printing it (assuming you properly sized the array to 9 rather than 8).

But assumingly i sized it to 9 rather than 8, when i call the binaryinput to print the input isn't the null going to appear again at the back of the output? Pardon my slowness in understand you because i am still learning the basics of C++.

or i could asummingly add = {0} at the back. But what does that do?

>But assumingly i sized it to 9 rather than 8, when i call the
>binaryinput to print the input isn't the null going to appear again at
>the back of the output?

No, you have to do it yourself. Local variables are not initialized to any value.

>or i could asummingly add = {0} at the back. But what does that do?
It initializes all elements of the array to 0.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.