Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a string to ascii to binary in C#?

Tags:

c++

c#

binary

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?

like image 454
Kredns Avatar asked Apr 10 '09 02:04

Kredns


3 Answers

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));
}
like image 142
Samuel Avatar answered Nov 15 '22 06:11

Samuel


Use an ASCIIEncoding class and call GetBytes passing the string.

like image 36
JP Alioto Avatar answered Nov 15 '22 06:11

JP Alioto


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);
like image 2
mqp Avatar answered Nov 15 '22 07:11

mqp