89

How can I get the ascii character of a given ascii code.

e.g. I'm looking for a method that given the code 65 would return "A".

Thanks

Dunc
  • 7,688
  • 10
  • 31
  • 38
  • Possible duplicate of [How to get a Char from an ASCII Character Code in c#](http://stackoverflow.com/questions/3414900/how-to-get-a-char-from-an-ascii-character-code-in-c-sharp) – Tim Pohlmann Oct 07 '16 at 08:59

9 Answers9

172

Do you mean "A" (a string) or 'A' (a char)?

int unicode = 65;
char character = (char) unicode;
string text = character.ToString();

Note that I've referred to Unicode rather than ASCII as that's C#'s native character encoding; essentially each char is a UTF-16 code point.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @Jon Skeet : if i set unicode = 128, why i am not bale to get character corresponding to it. – Iorn Man Aug 28 '13 at 08:19
  • @EthanHunt: Then you'll get U+0080, which is a control character. I suspect you're thinking of 128 in some different character encoding. – Jon Skeet Aug 28 '13 at 08:20
  • @Jon skeet : actually i want to display the character values for 0x80, 0x81- oxFF ( i convert these values to decimal i.e. 128-255 but i couldn't get the symbol corresponding to it.) how i can display those symbols too. – Iorn Man Aug 28 '13 at 09:10
  • @EthanHunt: What do you mean by "the character values"? U+0080 is a control character - how would you expect it to be displayed? Again, I suspect you're *actually* talking about values 128-255 in some other encoding, but you haven't told us what encoding that is. – Jon Skeet Aug 28 '13 at 09:20
  • @Jon Skeet:actually I am new to c#, i am doing a virtual keyboard like application in which i want to set these characters on buttons as its text. – Iorn Man Aug 28 '13 at 09:30
  • @EthanHunt: This has nothing to do with C#, and everything to do with you not understanding about Unicode, by the sounds of it. You need to find out which encoding you're actually interested in, and convert those values into Unicode characters. – Jon Skeet Aug 28 '13 at 09:32
  • @Jon Skeet : will you please take a look at below link. i think you will get what i am asking. http://stackoverflow.com/questions/18487948/display-control-characters-on-button-controls-as-its-text – Iorn Man Aug 28 '13 at 12:31
  • @EthanHunt: I've looked, and that question still shows no understanding of the issue, unfortunately. – Jon Skeet Aug 29 '13 at 05:42
37
 string c = Char.ConvertFromUtf32(65);

c will contain "A"

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
15

This works in my code.

string asciichar = (Convert.ToChar(65)).ToString();

Return: asciichar = 'A';

mhall
  • 3,671
  • 3
  • 23
  • 35
Bob Colin
  • 151
  • 1
  • 2
13

There are a few ways to do this.

Using char struct (to string and back again)

string _stringOfA = char.ConvertFromUtf32(65);

int _asciiOfA = char.ConvertToUtf32("A", 0);

Simply casting the value (char and string shown)

char _charA = (char)65;

string _stringA = ((char)65).ToString();

Using ASCIIEncoding.
This can be used in a loop to do a whole array of bytes

var _bytearray = new byte[] { 65 };

ASCIIEncoding _asiiencode = new ASCIIEncoding();

string _alpha = _asiiencode .GetString(_newByte, 0, 1);

You can override the type converter class, this would allow you to do some fancy validation of the values:

var _converter = new ASCIIConverter();

string _stringA = (string)_converter.ConvertFrom(65);

int _intOfA = (int)_converter.ConvertTo("A", typeof(int));

Here is the Class:

public class ASCIIConverter : TypeConverter
{
    // Overrides the CanConvertFrom method of TypeConverter.
    // The ITypeDescriptorContext interface provides the context for the
    // conversion. Typically, this interface is used at design time to 
    // provide information about the design-time container.
    public override bool CanConvertFrom(ITypeDescriptorContext context,
       Type sourceType)
    {
        if (sourceType == typeof(string))
        {
            return true;
        }
        return base.CanConvertFrom(context, sourceType);
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(int))
        {
            return true;
        }
        return base.CanConvertTo(context, destinationType);
    }


    // Overrides the ConvertFrom method of TypeConverter.
    public override object ConvertFrom(ITypeDescriptorContext context,
       CultureInfo culture, object value)
    {

        if (value is int)
        {
            //you can validate a range of int values here
            //for instance 
            //if (value >= 48 && value <= 57)
            //throw error
            //end if

            return char.ConvertFromUtf32(65);
        }
        return base.ConvertFrom(context, culture, value);
    }

    // Overrides the ConvertTo method of TypeConverter.
    public override object ConvertTo(ITypeDescriptorContext context,
       CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(int))
        {
            return char.ConvertToUtf32((string)value, 0);
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}
Keith Aymar
  • 876
  • 7
  • 10
2

Here's a function that works for all 256 bytes, and ensures you'll see a character for each value:

static char asciiSymbol( byte val )
{
    if( val < 32 ) return '.';  // Non-printable ASCII
    if( val < 127 ) return (char)val;   // Normal ASCII
    // Workaround the hole in Latin-1 code page
    if( val == 127 ) return '.';
    if( val < 0x90 ) return "€.‚ƒ„…†‡ˆ‰Š‹Œ.Ž."[ val & 0xF ];
    if( val < 0xA0 ) return ".‘’“”•–—˜™š›œ.žŸ"[ val & 0xF ];
    if( val == 0xAD ) return '.';   // Soft hyphen: this symbol is zero-width even in monospace fonts
    return (char)val;   // Normal Latin-1
}
Soonts
  • 20,079
  • 9
  • 57
  • 130
  • If the goal was to get a visible Unicode codepoint for every ASCII codepoint, then the [Control Pictures](http://unicode.org/charts/PDF/U2400.pdf) could be used to replace the [C0 Control](http://unicode.org/charts/PDF/U0000.pdf) characters. ␀ ␁ ␂ ␃ ␄ ␅ ␆ ␇ ␈ ␉ ␊ ␋ ␌ ␍ ␎ ␏… – Tom Blodget Feb 24 '17 at 16:31
  • 1
    @TomBlodget Nice to know, but that’s not an answer to the OP’s question. Feel free to submit another C# function that will do what the OP asked for. – Soonts Feb 24 '17 at 23:51
  • 1
    Note that ASCII only goes up to 127. Anything above that simply isn't ASCII, so at the very least your method is poorly named. – Jon Skeet Nov 14 '17 at 11:57
  • it also Handle unexpected numbers, awesome. – Sayed Muhammad Idrees Jan 05 '20 at 15:54
  • @TomBlodget, Is there a library that references the controls you mentioned? Or should we create it ourselves? – Ozgur Saklanmaz Jan 03 '22 at 07:32
1

It can also be done in some other manner

byte[] pass_byte = Encoding.ASCII.GetBytes("your input value");

and then print result. by using foreach loop.

web-tiki
  • 99,765
  • 32
  • 217
  • 249
1

Simply Try this:

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));
-2

I believe a simple cast can work

int ascii = (int) "A"

Carlos Valenzuela
  • 816
  • 1
  • 7
  • 19
  • Now he wanted help with the opposite.. Getting a char from a number – StefanE Jan 10 '11 at 16:13
  • 11
    Not that the given code will compile anyway - you can't convert from `string` to `int`. If it were `'A'` then it would work, but the cast would be redundant as there's an *implicit* conversion from `char` to `int`. – Jon Skeet Jan 10 '11 at 16:15
-3

Sorry I dont know Java, but I was faced with the same problem tonight, so I wrote this (it's in c#)

public string IncrementString(string inboundString)    {
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(inboundString.ToArray);
bool incrementNext = false;

for (l = -(bytes.Count - 1); l <= 0; l++) {
    incrementNext = false;

    int bIndex = Math.Abs(l);
    int asciiVal = Conversion.Val(bytes(bIndex).ToString);

    asciiVal += 1;

    if (asciiVal > 57 & asciiVal < 65)
        asciiVal = 65;
    if (asciiVal > 90) {
        asciiVal = 48;
        incrementNext = true;
    }

    bytes(bIndex) = System.Text.Encoding.ASCII.GetBytes({ Strings.Chr(asciiVal) })(0);

    if (incrementNext == false)
        break; // TODO: might not be correct. Was : Exit For
}

inboundString = System.Text.Encoding.ASCII.GetString(bytes);

return inboundString;
}