126

I want to get the ASCII value of characters in a string in C#.

If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.

How can I get ASCII values in C#?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
RBS
  • 3,481
  • 11
  • 31
  • 32
  • Do you mean you only want the alphabetic characters and not the digits? So you want "quality" as a result? Cause then talking about ASCII makes little sense. – Lars Truijens Dec 30 '08 at 16:35
  • I want Ascii of each character from that string ,Ascii of digits as well as ascii of word "quality" – RBS Dec 30 '08 at 16:36
  • What you mean is that you want the numeric ASCII value of each character in the string, assuming the entire string can be represented in ASCII. Your current wording is very confusing. – bzlm Jul 24 '09 at 08:14

15 Answers15

212

From MSDN

string value = "9quali52ty3";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

You now have an array of the ASCII value of the bytes. I got the following:

57 113 117 97 108 105 53 50 116 121 51

  • This shows me System.Byte[]. You need to loop through the chars in the word. Not sure how you got it to work. Helped the OP though which is what matters. – Nikos Sep 22 '18 at 09:35
  • Note: `Encoding.ASCII` is configured to emit the ASCII code unit for the replacement character ('?') for characters that are not in the ASCII character set. Other options—including throwing an exception—are available in the `Encoding` class. And, of course, other character encodings—especially UTF-8—are available, too; One should question whether it is ASCII that is actually wanted. – Tom Blodget Jan 11 '19 at 17:53
44
string s = "9quali52ty3";
foreach(char c in s)
{
  Console.WriteLine((int)c);
}
LeppyR64
  • 4,830
  • 1
  • 26
  • 33
23

This should work:

string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
    Console.WriteLine(b);
}
jason
  • 220,745
  • 31
  • 400
  • 507
9

Do you mean you only want the alphabetic characters and not the digits? So you want "quality" as a result? You can use Char.IsLetter or Char.IsDigit to filter them out one by one.

string s = "9quali52ty3";
StringBuilder result = new StringBuilder();
foreach(char c in s)
{
  if (Char.IsLetter(c))  
    result.Add(c);
}
Console.WriteLine(result);  // quality
Lars Truijens
  • 40,852
  • 6
  • 117
  • 137
4
string value = "mahesh";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

for (int i = 0; i < value.Length; i++)


    {
        Console.WriteLine(value.Substring(i, 1) + " as ASCII value of: " + asciiBytes[i]);
    }
VMAtm
  • 26,645
  • 17
  • 75
  • 107
mahesh
  • 41
  • 1
  • 5
4
string text = "ABCD";
for (int i = 0; i < text.Length; i++)
{
  Console.WriteLine(text[i] + " => " + Char.ConvertToUtf32(text, i));
}

If I remember correctly, the ASCII value is the number of the lower seven bits of the Unicode number.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Rauhotz
  • 7,334
  • 5
  • 36
  • 44
3

This program will accept more than one character and output their ASCII value:

using System;
class ASCII
{
    public static void Main(string [] args)
    {
        string s;
        Console.WriteLine(" Enter your sentence: ");
        s = Console.ReadLine();
        foreach (char c in s)
        {
            Console.WriteLine((int)c);
        }
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
M hasan
  • 31
  • 2
3

If you want the charcode for each character in the string, you could do something like this:

char[] chars = "9quali52ty3".ToCharArray();
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Neil Barnwell
  • 38,622
  • 28
  • 141
  • 213
3
byte[] asciiBytes = Encoding.ASCII.GetBytes("Y");
foreach (byte b in asciiBytes)
{
    MessageBox.Show("" + b);
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
moleatom
  • 31
  • 1
2

You can remove the BOM using:

//Create a character to compare BOM
char byteOrderMark = (char)65279;
if (sourceString.ToCharArray()[0].Equals(byteOrderMark))
{
    targetString = sourceString.Remove(0, 1);
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
2

Earlier responders have answered the question but have not provided the information the title led me to expect. I had a method that returned a one character string but I wanted a character which I could convert to hexadecimal. The following code demonstrates what I thought I would find in the hope it is helpful to others.

  string s = "\ta£\x0394\x221A";   // tab; lower case a; pound sign; Greek delta;
                                   // square root  
  Debug.Print(s);
  char c = s[0];
  int i = (int)c;
  string x = i.ToString("X");
  c = s[1];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
  c = s[2];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
  c = s[3];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);
  c = s[4];
  i = (int)c;
  x = i.ToString("X");
  Debug.Print(c.ToString() + " " + i.ToString() + " " + x);

The above code outputs the following to the immediate window:

a£Δ√

a 97 61

£ 163 A3

Δ 916 394

√ 8730 221A

Tony Dallimore
  • 11,977
  • 7
  • 28
  • 58
1

Or in LINQ:

string value = "9quali52ty3";
var ascii_values = value.Select(x => (int)x);
var as_hex = value.Select(x => ((int)x).ToString("X02"));
T.S.
  • 14,772
  • 10
  • 47
  • 66
ZagNut
  • 1,363
  • 12
  • 18
0

I want to get the ASCII value of characters in a string in C#.

Everyone confer answer in this structure. If my string has the value "9quali52ty3", I want an array with the ASCII values of each of the 11 characters.

but in console we work frankness so we get a char and print the ASCII code if i wrong so please correct my answer.

 static void Main(string[] args)
        {
            Console.WriteLine(Console.Read());
            Convert.ToInt16(Console.Read());
            Console.ReadKey();
        }
  • This answer could use a little more explanation. If you have a colleague more fluent in English, with respect you should ask for help. – O. Jones Jun 24 '17 at 11:47
  • my explanation is very simple because my code is very simple without any variables but used a simple concept how can print ASCII value individual simple get a char and convert the char in integer value so please you implement this and if i have mistake in my explanation so please you correct this thanks – MA Nadeem Jun 24 '17 at 13:16
0

Why not the old fashioned easy way?

    public int[] ToASCII(string s)
    {
        char c;
        int[] cByte = new int[s.Length];   / the ASCII string
        for (int i = 0; i < s.Length; i++)
        {
            c = s[i];                        // get a character from the string s
            cByte[i] = Convert.ToInt16(c);   // and convert it to ASCII
        }
        return cByte;
    }
-1
    string nomFile = "9quali52ty3";  

     byte[] nomBytes = Encoding.ASCII.GetBytes(nomFile);
     string name = "";
     foreach (byte he in nomBytes)
     {
         name += he.ToString("X02");
     }
`
     Console.WriteLine(name);

// it's` better now ;)

Monarc Dev
  • 26
  • 3
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Dharman Mar 19 '20 at 11:42
  • Gives a compile error: "Unexpected character". The two ` after the ToString probably shouldn't be there. – BDL Mar 19 '20 at 14:32