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