You are here:

C/scanf and adding binary numbers

Advertisement


Question
QUESTION: Hi,

I'm wondering how you'd do this. I realize that scanf function converts ascii directly to binary for you, so when you enter two integers for example, you can simply add the two values and get the sum.

But now, I'd like to use the gets function to read in the numbers that user wants and then have that result converted to binary numbers which then I would like to have them added together. The code below I write can convert decimal values into binary but that's not what I wanted obviously.

So basically, I wanted to be able to have user enter in values, have those numbers converted into binary and then have the result added together WITHOUT USING THE SCANF function. Thanks for all the help, hope you understand my question here.


#include <stdio.h>

void main()
{  
int i=0,n,j,b[100];

while (n>0)
{
b[i]=n%2;
n=n/2;
i++;
}
printf("\n\t\tBinary is: ");
j=i-1;
for (i=j;j>=0;j--)
{
printf("%d", b[j]);
}

ANSWER: Hello Mike.

I think I do understand your question. Let me clarify one thing. You do not need to translate a number into "binary". You need to translate a set of characters into an integer. The integer is a number and numbers are stored in the computer memory using binary but you do not use binary when doing the addition. You simply use integers.

Below is a program which takes a string of input characters and turns it into an integer in memory. It uses the gets function and the gets function puts the characters into the input array. The program does no error checking so it assumes the user does not overflow the input array with more characters than it can hold, and it assumes the user inputs only digits. You should at least add error checking to ensure that each character is a digit character. You can use the isdigit function for that. You should also put the code into its own function so it can be called twice, once for each number you want to add together.

Finally, if you really want to see the number in its binary form, you will need to use bit shifting and bit and-ing to extract the bits for printing. I'll leave that for you to do.

Have a look at the program below. Run it. Run it with a debugger. That will help you to understand it. Then, modify it to suit your assignment.

#include <stdio.h>
#include <string.h>

int main()
{  
   char input[64]; /* An input array to hold the user input */
   int  number = 0; /* always important to initialize your variables */
   int  inputLen; /* The length of the user input */
   int  inputIx; /* an index into the input array */

   printf("Input a number\n");
   gets(input);

   printf("The input is '%s'\n", input);
   inputLen = strlen(input);


   /* Loop to convert the characters into a number */
   /* This is what scanf() and atoi() do */
   for (inputIx = 0; inputIx < inputLen; ++inputIx)
   {
       /* get the character */
       char character = input[inputIx];

       /* subtract the value of the '0' character so that the
       character now contains the value meant by the input character.

       Notice when I mean character, I use single quotes. Without the quotes, I mean the number

       For example, the character '0' is represented in memory by 48.
       Do an internet search on ascii to get the character codes.

       The character '1' is 49
       The character '2' is 50 and so on
       By subtracting the value of '0' (which is 48) from the character we get this:
       '0' - '0' = 48 - 48 = 0
       '1' - '0' = 49 - 48 = 1
       '2' - '0' = 50 - 48 = 2
       */
       character = character -'0';

       /* Add in the character contribution to the number */
       number = number * 10;
       number = number + character;
   }

   printf("The number decimal is %d\n", number);
   printf("The number in hex is 0x%0X\n", number);


   return 0;
}

---------- FOLLOW-UP ----------

QUESTION: I think I was asking also, if you could convert from string directly to integer or binary without having to go through ascii, if that is even possible....

ANSWER: The atoi function will take a numeric string and return the integer value for that string. It basically does what I did in my program. I wasn't sure what level of detail you were looking for. Once you have your input, you can do:

number = atoi(input)

You can get rid of the loop in my program and the line that calculates inputLen.

---------- FOLLOW-UP ----------

QUESTION: Hi once more, here's the modifications I made to your program, but it doesn't seem to work in terms of the adding of the two numbers entered. Sometimes the program will give out the right answer, sometimes it doesn't. Why is that?


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define TRUE 1

int main()
{  
  int i = 0;
  int num_store = 0;
  int k = 0;
  
  printf("ADD
");
  printf("---
");
  for(i=0; i <2; i++)
  {
     char input[64];  //An input array to hold the user input
     int  number = 0;
     int j = 0;
     int  inputLen; //The length of the user input
     int  inputIx; //an index into the input array

     while (TRUE)
     {
        printf("Input a number: ");
        gets(input);
        
        if(isdigit(input[j]))
         break;
        
        printf("
ERROR: invalid number entered. Please Re-Enter.

");
     }

     // printf("The input is '%s'
", input);
     inputLen = strlen(input);

     // Loop to convert the characters into a number
     for (inputIx = 0; inputIx < inputLen; ++inputIx)
     {
     // get the character
        char character = input[inputIx];

      /* subtract the value of the '0' character so that the
      character now contains the value meant by the input character.

      The character '1' is 49
      The character '2' is 50 and so on
      By subtracting the value of '0' (which is 48) from the character we get this:
      '0' - '0' = 48 - 48 = 0
      '1' - '0' = 49 - 48 = 1
      '2' - '0' = 50 - 48 = 2
      */
        character = character - '0';

      // Add in the character contribution to the number
        number = number * 10;
        number = number + character;
        num_store = number;
     }
  }
  
  k = num_store;
  printf("
Sum = %d
", k + num_store);
  return 0;
}

Answer
Hello Mike

You have a loop
for(i=0; i <2; i++)

to input the two numbers. You know that you need to store one of the numbers in a temporary location while you get the second number, so you use num_store. But the second time through the loop the same thing happens. The number is stored in num_store, causing the first number to be overwritten. You need different logic on the second time around. Specifically, you need to store only the first number into num_store. Then when printing the sum, you add number + num_store. You don't need the k variable but you will need to move your declaration of int number out of the for loop, to the top of main. It can be done in that way but a cleaner design would be to create a function like this:

int getNumber()
{
}

which would read from the keyboard, do the conversion from ascii string to integer, and return the integer. Then your main program would look like this:

int main(void)
{
   int number1;
   int number2;

   number1 = getNumber();
   number2 = getNumber();
   printf("Sum = %d", number1 + number2);
}

Your idea with the for(i=0; i <2; i++) loop is to reuse your code and that is good, but using functions is a better way to reuse the code. In the second method, the for loop goes away, and everything in the for loop goes into the getNumber function.


Try to correct your code using one of the ideas I suggested and let me know how it goes. Your error checking also has some problems but I'll advise you about that after you make your corrections.

Let me know if my instructions are not clear.

Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.