Click to See Complete Forum and Search --> : Decimal to Binary Conversion Question


kitsune84
April 20th, 2005, 05:44 PM
I'm still pretty new to this language, so this is likely a stupid mistake...but I'd really appreciate it if anyone could help me out. I'm trying to convert a user-entered decimal number to binary. I'm using a simple GUI with textboxes and buttons.


//decimalTxt & binaryTxt are two textboxes

private: System::Void dec2binBtn_Click(System::Object * sender, System::EventArgs * e)
{
int number = System::Int32::Parse(decimalTxt->Text);
String* binary;
int remainder;

if (number == 0)
binaryTxt->Text = "0";
else
{
while (number != 0)
{
remainder = int(number) % 2;
binary->Concat(remainder.ToString());
number = number / 2;
}

binaryTxt->Text = binary;
}

}


As-is, the text in binaryTxt does not change when button is clicked. And I am aware that this (should) give me the binary number, but backwards. I haven't tried flipping it, yet, since this doesn't work. Any ideas?

wildfrog
April 20th, 2005, 07:04 PM
String::Concat(...) doesn't do anything with the original string, it returns a new concatenated string.


int yourInt = 1257;
String* yourBinary = "";

while (yourInt != 0)
{
yourBinary = String::Concat((yourInt & 1).ToString(), yourBinary);
yourInt = yourInt / 2;
}

Console::WriteLine("{0}", yourBinary);


- petter

cilu
April 25th, 2005, 08:25 AM
Use std::bitset.

kitsune84
April 25th, 2005, 09:03 AM
Thanks, guys! It works now. :)