binary 2 decimal

Status
Not open for further replies.

el_presidente

Solid State Member
Messages
9
I'm trying to write a program in MS visual c++ that will convert a binary string into a decimal. I know what the formula is and all that, I just can't think of anything that can access each member of the string and applying the formula. I've tried using arrays, but I can't seem to get this to work. What's the simplist way to do this?
 
Thanks for the help. I got it to work, but I had to make it so you have to enter each member of the array at a time. It calulates only for a four digit binary number correctly, but theres a run-time error every time. How can I make it so I can enter how ever many digits I want, and get rid of the error. Here's what I got.

#include <iostream>
using namespace std;
int main()
{
int hold1;
int hold2;
int hold3;
int hold4;
int main_hold;
int BinString[3];
cin >> BinString[0];
cin >> BinString[1];
cin >> BinString[2];
cin >> BinString[3];
hold1 = BinString[3] * 1;
hold2 = BinString[2] * 2;
hold3 = BinString[1] * 4;
hold4 = BinString[0] * 8;
main_hold = hold1 + hold2 + hold3 + hold4;
cout << main_hold << endl;
return 0;
}
 
I don't think so. It counts BinString[0] as a member of the array, because computers count 0,1,2,3,4,5 and so on, while most people forget about the zero. That's why if you were to declare the array as int BinString[0]; there is only one member in it.
 
That's why if you were to declare the array as int BinString[0]; there is only one member in it.
Actually, it means you've declared an array that can hold no values.

binstring should be 4 shouldnt it?
Yes.

el_presidente, you're confusing the difference between accessing and declaring an array. First, when you declare an array, the number in the brackets specifies the number of elements the array can hold. For instance:
Code:
int array[5];
declares an integer array that can hold 5 integer elements.

On the other hand, when you want to access the 5th element in the array, you would use the following syntax:
Code:
array[4];
 
yea, i think i did mix that up. is there any way i can enter the entire thing all in one shot rather than pressing enter after each time and so i can enter as many as i need to.
 
Yup, you can just read the enitre string in at the beginning. I'm not familiar with C++, but in C you would just do a scanf to read in the string.

Then you can access each character of the string as an element of an array.

So something like the following.
This is in C
Code:
int i;
double sum;
char str[100];

for(i=0, i<100; i++)
   char[i]=0;

scanf("%s", str);

for(i = 0, i < 100, i++){
   sum += char[i] * pow(2, i);
}

return sum

double pow(int base, int exp){
   double sum = 1;
   int i;
   for(i=0, i<exp, i++)
      sum = sum*base;

  return sum;
}

My syntax might be a bit off since I haven't coded in a bit, but the format is correct.
 
Status
Not open for further replies.
Back
Top Bottom