views:

611

answers:

5

There are a million posts on here on how to convert a character to its ASCII value.
Well I want the complete opposite.
I have an ASCII value stored as an int and I want to display its ASCII character representation in a string.

i.e. please display the code to convert the int 65 to A.

What I have currently is String::Format("You typed '{0}'", (char)65)

but this results in "You typed '65'" whereas I want it to be "You typed 'A'"

I am using C++/CLI but I guess any .NET language would do...

(edited post-humously to improve the question for future googlers)

+2  A: 

For ASCII values, you should just be able to cast to char? (C#:)

char a = (char)65;

or as a string:

string a = ((char)65).ToString();
Marc Gravell
+4  A: 

In C++:

int main(array<System::String ^> ^args)
{
    Console::WriteLine(String::Format("You typed '{0}'", Convert::ToChar(65)));
    return 0;
}
Austin Salonen
And we have a winner! Thanks :)
demoncodemonkey
A: 

Just cast it; couldn't be simpler.

// C#
int i = 65;
Console.WriteLine((char)i);
Michael Petrotta
+6  A: 

There are several ways, here are some:

char c = (char)65;
char c = Convert.ToChar(65);
string s = new string(65, 1);
string s = Encoding.ASCII.GetString(new byte[]{65});
Guffa
The last two should be appended with `[0]`. That is, for example, `char c = new string(65, 1)[0];`.
Jason
@Jason: Yes, you can do that it you really want it as a char. If he's going to concatenate it with other strings there is no point in creating a string to create a char that is going to be turned into a string again before it can be concatenated.
Guffa
+1  A: 

The complex version, of course, is:

public string DecodeAsciiByte(byte b) {
    using(var w = new System.IO.StringWriter()) {
        var bytebuffer = new byte[] { b };
        var charbuffer = System.Text.ASCIIEncoding.ASCII.GetChars(bytebuffer);
        w.Write(charbuffer);
        return w.ToString();
    }
}

Of course, that is before I read the answer using the Encoding.GetString method. D'oh.

public string DecodeAsciiByte(byte b) {
    return System.Text.Encoding.ASCII.GetString(new byte[] { b });
}
Justice