A while back (freshman year of high school) I asked a really good C++ programmer who was a junior to make a simple application to convert a string to binary. He gave me the following code sample:
void ToBinary(char* str)
{
char* tempstr;
int k = 0;
tempstr = new char[90];
while (str[k] != '\0')
{
itoa((int)str[k], tempstr, 2);
cout << "\n" << tempstr;
k++;
}
delete[] tempstr;
}
So I guess my question is how do I get an equivalent to the itoa function in C#? Or if there is not one how could I achieve the same effect?
This is very easy to do with C#.
var str = "Hello world";
With LINQ
foreach (string letter in str.Select(c => Convert.ToString(c, 2)))
{
Console.WriteLine(letter);
}
Pre-LINQ
foreach (char letter in str.ToCharArray())
{
Console.WriteLine(Convert.ToString(letter, 2));
}
Use an ASCIIEncoding class and call GetBytes passing the string.
It's not clear precisely what you want, but here's what I think you want:
return Convert.ToString(int.Parse(str), 2); // "5" --> "101"
This isn't what the C++ code does. For that, I suggest:
string[] binaryDigits = str.Select(c => Convert.ToString(c, 2));
foreach(string s in binaryDigits) Console.WriteLine(s);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With