binary to decimal conversion program, having probs

Thread Starter

count_volta

Joined Feb 4, 2009
435
Sorry forgot to say that this is programming in C.

Hi, I'm doing some programming practice for fun and decided to write a simple program that converts binary to decimal based on the well known algorithm. For those who don't know for some reason, the algorithm is as follows:

Say you want to convert 1101 to decimal.
You do: 1*2^0 + 1*2^2 + 1*2^3 = 13

Below is my code. The program runs but gives wrong answers. I don't understand why. I checked that the array contains the binary bits that the user enters. Then I use each element of the array as the bit location LSB to MSB, and loop through them to get the sum.

Rich (BB code):
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int a[32],n,i,j,m;
    int sum =0;
    double g = 2;
    
printf("Enter the number of bits in your binary number\n");
scanf("%d",&n);
printf("Enter the binary number with a space after every bit\n");
for (i=0;i< n;i++);
{
scanf("%d",&a);  // get binary number from user and enter it into array a
}

for (j=0; j<n;j++);

{
    if (a[j] == 1); // test if the bit is a 1, if so do 2^ bit index
    {
    
    m =  pow(g, j);
    sum = sum + m; // add all the 2^ bit indices for the bits that are 1 to get the decimal number
        }
}

printf("Your binary number in base 10 is %d\n", sum );

}
 

Thread Starter

count_volta

Joined Feb 4, 2009
435
I think the problem may have something to do with the double data type. According to my compiler, to use the pow function at least one of the arguments needs to be a double. I made the variable "g" a double and made it equal to 2. Until I did that, it didn't even compile.

See below.

 

Attachments

debjit625

Joined Apr 17, 2010
790
According to my compiler, to use the pow function at least one of the arguments needs to be a double.
simple ,cast it to double ... see how I did it

Now their are problems in code logic and also in the way you used the language C so here is a simple way to do that i.e.. the way you wanted but their are better ways and faster algo anyway ,first never do this
Rich (BB code):
scanf("%d",&a);  

scanf's second parameter as per you will be an address of an int variable or a pointer to an int variable now the array is itself a pointer to the first element you cant pass its address...

Something like this will work..
Rich (BB code):
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
char a[32] = {0};
int n=0,i=0,j=0;
int sum =0;

printf("Enter the number of bits in your binary number\n");
scanf("%d",&n);
printf("Enter the binary number\n");
scanf("%s",a);
for (j=(n-1);j>=0;j--)
{
if(a[j]== '1')
{
sum = sum + 1 * pow(2.0,(double)(3-j));
}
else
{
sum = sum + 0 * pow(2.0,(double)(3-j));
}
}
printf("Your binary number in base 10 is %d\n", sum );
}
Another thing always initialize your variables.

Good Luck
 

debjit625

Joined Apr 17, 2010
790
One more thing ,always return value for your main function under a RTOS like windows ...
Rich (BB code):
int main(void)
{
 //All code goes here.............
 return 0;
}
 
Sorry forgot to say that this is programming in C.

Hi, I'm doing some programming practice for fun and decided to write a simple program that converts binary to decimal based on the well known algorithm. For those who don't know for some reason, the algorithm is as follows:

Say you want to convert 1101 to decimal.
You do: 1*2^0 + 1*2^2 + 1*2^3 = 13

Below is my code. The program runs but gives wrong answers. I don't understand why. I checked that the array contains the binary bits that the user enters. Then I use each element of the array as the bit location LSB to MSB, and loop through them to get the sum.

Rich (BB code):
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int a[32],n,i,j,m;
    int sum =0;
    double g = 2;
 
printf("Enter the number of bits in your binary number\n");
scanf("%d",&n);
printf("Enter the binary number with a space after every bit\n");
for (i=0;i< n;i++);
{
scanf("%d",&a);  // get binary number from user and enter it into array a
}
 
for (j=0; j<n;j++);
 
{
    if (a[j] == 1); // test if the bit is a 1, if so do 2^ bit index
    {
 
    m =  pow(g, j);
    sum = sum + m; // add all the 2^ bit indices for the bits that are 1 to get the decimal number
        }
}
 
printf("Your binary number in base 10 is %d\n", sum );
 
}


The problem seems to be that you misunderstand syntax of conditional (if())and loop (for()) statements.

In C you may have after if() and for() clause either a simple statement (terminated with ";") or a compouns statement (embraced with {} and without a ";" at the ent). C also allows empty statements (bare ";") and compound statements clocks ({}) without any loop or conditional.

Your code:

for (i=0;i< n;i++);
{
scanf("%d",&a); // get binary number from user and enter it into array a
}


actually means:
"for i to n DO NOTHING", then
"get a SINGLE integer from stdin"

Similar things occur with your next "for": if does NOTHING n times, then ONE time executes the compound statement. Inside that, you have the same problem with "if()" - if the condition is true it does NOTHING, then unconditionally executes

{

m = pow(g, j);
sum = sum + m; // add all the 2^ bit indices for the bits that are 1 to get the decimal number
}
Remember, at this point you have j == n. So that's what your output is - always 1 ^ n (number of bits), no matter what the bit values are.

In order to get the behavior that you wanted, remove all ";"s after if() and for()s.

BTW, when running the corrected program you may get a hint why "big endian" and "little endian" representations were invented.
 

Thread Starter

count_volta

Joined Feb 4, 2009
435
The problem seems to be that you misunderstand syntax of conditional (if())and loop (for()) statements.

In C you may have after if() and for() clause either a simple statement (terminated with ";") or a compouns statement (embraced with {} and without a ";" at the ent). C also allows empty statements (bare ";") and compound statements clocks ({}) without any loop or conditional.

Your code:



actually means:
"for i to n DO NOTHING", then
"get a SINGLE integer from stdin"

Similar things occur with your next "for": if does NOTHING n times, then ONE time executes the compound statement. Inside that, you have the same problem with "if()" - if the condition is true it does NOTHING, then unconditionally executes



Remember, at this point you have j == n. So that's what your output is - always 1 ^ n (number of bits), no matter what the bit values are.

In order to get the behavior that you wanted, remove all ";"s after if() and for()s.

BTW, when running the corrected program you may get a hint why "big endian" and "little endian" representations were invented.
Thank you, I removed the semicolons after the if and for and it works. :D

And yes you are right about the big and little endian. You have to enter the LSB first and MSB last because the loop accesses the LSB first. It looks backwards in the command console.

So what exactly do the semicolons mean? Nobody really explained to me. They just say, after every statement, put them there. Does it specify the end of a statement?
 

Thread Starter

count_volta

Joined Feb 4, 2009
435
I actually modified the code so that you can enter the binary number, MSB first and LSB last.

Rich (BB code):
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int a[32],n,i,j,m;
    int sum =0;
    double g = 2;
    
printf("Enter the number of bits in your binary number: ");
scanf("%d",&n);
printf("Enter the binary number with a space after every bit:\n\n");
for (i=(n-1); i>=0; i--)
{
scanf("%d",&a);  // get binary number from user and enter it into array a
}

for (j=0; j<n;j++)

{
    if (a[j] == 1) // test if the bit is a 1, if so do 2^ bit index
    {
    
    m =  pow(g, j);
    sum = sum + m; // add all the 2^ bit indices for the bits that are 1 to get the decimal number
        }
}

printf("Your binary number in base 10 is %d\n\n", sum );

return 0;


}
If anybody wants to use this program, go ahead. I just did this for fun. Now I'm going to write some code to go from decimal to binary.
 
Last edited:

Thread Starter

count_volta

Joined Feb 4, 2009
435
simple ,cast it to double ... see how I did it

Now their are problems in code logic and also in the way you used the language C so here is a simple way to do that i.e.. the way you wanted but their are better ways and faster algo anyway ,first never do this
Rich (BB code):
scanf("%d",&a);  
scanf's second parameter as per you will be an address of an int variable or a pointer to an int variable now the array is itself a pointer to the first element you cant pass its address...

Something like this will work..
Rich (BB code):
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main()
{
char a[32] = {0};
int n=0,i=0,j=0;
int sum =0;

printf("Enter the number of bits in your binary number\n");
scanf("%d",&n);
printf("Enter the binary number\n");
scanf("%s",a);
for (j=(n-1);j>=0;j--)
{
if(a[j]== '1')
{
sum = sum + 1 * pow(2.0,(double)(3-j));
}
else
{
sum = sum + 0 * pow(2.0,(double)(3-j));
}
}
printf("Your binary number in base 10 is %d\n", sum );
}
Another thing always initialize your variables.

Good Luck


You are right, but then why does the program work? I removed the extra semicolons and it works. If the second argument of scanf is a pointer, and the array is a pointer to the first element, what is the problem?
 
Semicolons don't have a definition in C which can be written in one sentence. A semicolon is used:
1) To mark the end of a non-compound statement
2) To mark the end of a declaration
3) After while() in a do() statement (but not in a while() statement: a bare semicolon after while() in a while statement will have a meaning of "while [condition] do NOTHING"
4) To separate three expressions in a for() statement

Daniel
 
simple ,cast it to double ... see how I did it

Now their are problems in code logic and also in the way you used the language C so here is a simple way to do that i.e.. the way you wanted but their are better ways and faster algo anyway ,first never do this
Rich (BB code):
scanf("%d",&a);  

scanf's second parameter as per you will be an address of an int variable or a pointer to an int variable now the array is itself a pointer to the first element you cant pass its address...


With regard to scanf() behavior the OP's code was absolutely correct. In C "[]" operator has higher precedence than unary "&", so "&a" is equivalent to "&(a)" (address of a, which is an integer), and NOT "(&a)" as you seem to suggest.

BTW, what's the meaning of "3-j" in your code?
 

Thread Starter

count_volta

Joined Feb 4, 2009
435
I am having another strange problem. I am using Visual C++ 2008 Express as my compiler. After I compile the program, and press "start without debugging", everything works fine. It converts my binary number and finishes with "press any key to continue".

When I press "start debugging", all it does is ask for the number of bits in the binary number, then asks to enter the binary number, and when I enter it, the console window just closes without displaying the converted number and displaying the "press any key" message.

I found my exe file and when I run it, the same thing happens, the window just closes. Did I not do something? I just started an empty project, and added my .cpp file as the source file in Visual C. Do I maybe need to add a header file or something. I never made an actual exe file before. Please help me out. Thanks.
 

thatoneguy

Joined Feb 19, 2009
6,359
What is happening is the number is displaying, and the window is instantly closing, so you don't see it.

Create a shortcut to cmd, and set the properties to not close on program completion. Or, hit <WinKey>+R, type 'cmd' and hit enter. It will pop up a command window, change directory to where your program is and run it, it will stay open and return to c:\whatever\your\path\is when finished.

A better option is to modify the program:

At the beginning, have the prompt be:
"Input number of digits, or 'd' for converting decimal to binary, 'q' to quit"

<get input>

If it is a number, go through the routine above. If the input was not a number, then -> If the input was d, go to the decimal->binary routine, if it is q, then exit the program with return(0);

Or you could have it go in an infinite loop with what you have, and use CTRL+C to stop the program, but that's a bit sloppy.

Better yet is to create a form window to fill out and show results in, I'm used to X Win/*nix, but it isn't too hard with the visual dev tools.
 

Thread Starter

count_volta

Joined Feb 4, 2009
435
I wrote a little program to go the other way too. Decimal to binary. This one was more tricky and challenging, but I got it. I plan to have both programs in one, using a switch statement.

I will post the exe here later if anyone can use such a program. I just did this for fun and programming practice. Here is the code.

Rich (BB code):
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int dec,i;
int quotient;
int remainder;
int binary[32];
int j;



printf("Please enter the decimal number which you want to convert to binary:\n");
printf("\n");
scanf("%d", &dec);
printf("\n");

quotient = dec;
printf("Your decimal number in binary is: ");
i=0;

while (quotient != 0)  // while quotient is not zero, keep dividing by 2.
{
    
    remainder = quotient % 2; 
    quotient = quotient / 2; // divide your decimal number by 2, and divide the answer by 2 and keep going until quotient is 0.
    
    if (remainder == 0 ) // if remainder is 0, the binary bit is 0

        binary = 0;
    else
    {
        binary = 1;  // if remainder is 1, the binary bit is 1
    }
        i++;
    
}

if (dec != 0) // if your decimal number is not zero, print the array backwards, i.e. MSB to LSB
{
for (j=(i-1); j>=0; j--)
{
printf("%d", binary[j]);
}
printf("\n\n");
}
else  // if your decimal number is zero, so is your binary number. 
{
    printf("0\n\n");

}

return 0;


}
 
Last edited:

Thread Starter

count_volta

Joined Feb 4, 2009
435
I have attached the completed program .exe to this post. This combines the two. It can do decimal to binary and binary to decimal.

I have sent the exe to my friend who uses Windows 7 and he had errors when he tried to run it. It runs fine on my Windows XP.

Can other people please try running it and tell me if it works. I wonder if I didn't add some necessary code or something. I never compiled an actual exe before.
 

Attachments

thatoneguy

Joined Feb 19, 2009
6,359
He may need to install the visual C runtime environment to get the .DLLs called by your compiled program.

You can eliminate this need by compiling it as a "static" binary, but the resulting .exe file will be quite huge.
 

Thread Starter

count_volta

Joined Feb 4, 2009
435
He may need to install the visual C runtime environment to get the .DLLs called by your compiled program.

You can eliminate this need by compiling it as a "static" binary, but the resulting .exe file will be quite huge.
That is weird because the only libraries in my program are

Rich (BB code):
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
I thought these libraries are default. What do people do when making a program that is supposed to run on Windows and make sure that the user has all the dependencies?
 

thatoneguy

Joined Feb 19, 2009
6,359
Functions such as scanf, printf, etc. are all in the runtime library. The visual C runtime environment is usually installed with many other applications, so most everybody already have a few versions installed and they don't bump into the problem

It's a free download from microsoft, you just need to get the correct version to match your compiler version. There are visual c and visual basic run time libraries for many versions, which makes it kind of a headache. Creating an .msi installer will include everything needed and set it up, you could do it in that method instead of sending the bare .exe file.
 
Top