tags:

views:

1984

answers:

4

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?

+1  A: 

Use an ASCIIEncoding class and call GetBytes passing the string.

JP Alioto
This doesn't seem to me to have anything to do with the question. I might be wrong, because the question is quite vague except for the somewhat odd sample code.
mquander
The code sample is a little odd but you should know what it does. It gets each char value and converts it to its binary representation and outputs it.
Samuel
Sorry, I didn't mean to be vague. This was just a hobby project I was working on.
Lucas McCoy
+2  A: 

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);
mquander
+3  A: 

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));
}
Samuel
+1  A: 

Thanks, this is great!! I've used it to encode query strings...

protected void Page_Load(object sender, EventArgs e)
{
    string page = "";
    int counter = 0;
    foreach (string s in Request.QueryString.AllKeys)
    {
        if (s != Request.QueryString.Keys[0])
        {
            page += s;
            page += "=" + BinaryCodec.encode(Request.QueryString[counter]);
        }
        else
        {
            page += Request.QueryString[0];
        }
        if (!page.Contains('?'))
        {
            page += "?";
        }
        else
        {
            page += "&";
        }
        counter++;
    }
    page = page.TrimEnd('?');
    page = page.TrimEnd('&');
    Response.Redirect(page);
}

public class BinaryCodec {

public static string encode(string ascii)
{
    if (ascii == null)
    {
        return null;
    }
    else
    {
        char[] arrChars = ascii.ToCharArray();
        string binary = "";
        string divider = ".";
        foreach (char ch in arrChars)
        {
            binary += Convert.ToString(Convert.ToInt32(ch), 2) + divider;
        }
        return binary;
    }
}

 public static string decode(string binary)
{
    if (binary == null)
    {
        return null;
    }
    else
    {
        try
        {
            string[] arrStrings = binary.Trim('.').Split('.');
            string ascii = "";
            foreach (string s in arrStrings)
            {
                ascii += Convert.ToChar(Convert.ToInt32(s, 2));
            }
            return ascii;
        }
        catch (FormatException)
        {
            throw new FormatException("SECURITY ALERT! You cannot access a page by entering its URL.");
        }
    }
}

}

Jarrod