2 Replies - 11642 Views - Last Post: 27 July 2008 - 10:46 AM Rate Topic: -----

#1 hbgrg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-July 08

Binary to Decimal converter

Post icon  Posted 26 July 2008 - 10:51 PM

I am trying to convert from binary to decimal but no matter what 8 digit sequence I enter it gives me 255 (the binary equivalent to 11111111) please tell me what I am doing wrong!
#include <iostream>
using namespace std;
void ConvToBin (char bit[100])
{
	int i = 8;
	int bin = 1;
	int total = 0;
	for (i; i > 0; i--)
	{
		if (bit[i] = 1)
		{
			total = bin + total;
		}
		bin = (bin * 2);
	}
	cout << total;
};
int main ()
{
	char bit[100];
	cout << "Please enter an eight digit binary sequence using only 1's and 0's: ";
	cin >> bit;
	ConvToBin (bit);
	return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Binary to Decimal converter

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4356
  • View blog
  • Posts: 12,175
  • Joined: 18-April 07

Re: Binary to Decimal converter

Posted 26 July 2008 - 11:19 PM

Well there are easier ways of converting from binary to decimal but I will work with what you have to get it to work for you...


#include <iostream>
using namespace std;
void ConvToBin (char bit[100])
{
    int i = 7;
    int bin = 1;
    int total = 0;

	// Starting at index 7 and going down to 0 (8 numbers)
    for (i; i >= 0; i--)
    {
		// bit array here is a char array, so you have to compare against '1' not integer 1
        if (bit[i] == '1')
        {
            total = bin + total;
        }
        bin = (bin * 2);
    }
    cout << total;
}

int main ()
{
    char bit[100];
    cout << "Please enter an eight digit binary sequence using only 1's and 0's: ";
    cin >> bit;
    ConvToBin (bit);
    return 0;
}



Notice that we compare each bit from 0 to 7 not 8. Secondly, it is a char array so you have to compare against character '1' not integer 1. This should start then working for you.

Oh and congrats on being my 4000th post.

"At DIC we be 4000th posting ninjas, 4000 now, only 23.9 million more to go!" :snap:
Was This Post Helpful? 0
  • +
  • -

#3 hbgrg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-July 08

Re: Binary to Decimal converter

Posted 27 July 2008 - 10:46 AM

oooooo I get it thank you very much it makes sense now =]
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1