Convert binary to decimal

I want to ask how to convert 32 bit binary to decimal. As far as I could is convert 10 bit with this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  private: System::Void Button1_Click(System::Object^ sender, System::EventArgs^ e) 
	{
		
		int i, num, binVal, decVal = 0, baseVal = 1, rem; // rem = remainder = sisa;
		num = 1111111111;
		binVal = num;
		while (num > 0)
		{
			rem = num % 10;
			decVal = decVal + rem * baseVal;
			num = num / 10;
			baseVal = baseVal * 2;
		}
		textBox1->AppendText("Binary Number: " + binVal);
		textBox2->AppendText("\nDecimal: " + decVal);
	}


I am using C++/CLI fyi. thanks for the help
1
2
3
4
5
    ...
    int num = 0b11111111111111111111111111111110;
    ...
    textBox1->AppendText( "Binary Number: " + std::bitset<32>(num).to_string() );
    textBox2->AppendText( "\nDecimal: " + std::to_string(num) );
Last edited on
if you want to do it yourself for study,
you can basically construct an integer by iterating the string.
in pseudoC:

string s = "1111"
int result = 0;
do
{
result << 1; //shift up. //first time zero has no effect.
result += (letter=='1'); //if the equality is true, add 1, else add zero
} //while have not done every letter

there are more efficient ways to do it if you were writing the c++ library you can do a lookup table for 8 bits worth and do it a byte at a time, for one.
Last edited on
Thanks everyone, i found the solution that really simple (thanks especially to nuderobmonkey)

The code is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private: System::Void Button1_Click(System::Object^ sender, System::EventArgs^ e) 
	{
		int num, binVal, decVal = 0, baseVal = 1, rem; // rem = remainder = sisa;
		num = 0b00000110000111100111001110101100;
		binVal = num;
		while (num > 0)
		{
			rem = num % 10;
			decVal = decVal + rem * baseVal;
			num = num / 10;
			baseVal = baseVal * 2;
		}
		textBox2->AppendText("Decimal: " + binVal);
	}


I just change the initialization of num with '0b' and in the textBox2 i add + binVal. Not so different with my first code but it works. Thanks anyway
Last edited on
Why do you still have lines 6 - 12? @nuderobmonkey's point was that inside the computer numbers are numbers are numbers. It's only the representation that changes. The conversion is done automagically, and you don't have to do anything.

By using a binary representation in line 4, the value 'num' is assigned, and can be printed out in decimal format in line 13. You don't have to do anything more. As a matter of fact, whatever you do in lines 6 - 12 is being ignored, so it's wasted code.
Registered users can post here. Sign in or register to post.