0

I need to get the ASCII values for individual string in C#

Say for example I have an array

string[] ar =  new string{"1", "2", "3", "4", "5"};

I need to get the ASCII values of these individual array elements. Like for ar[0], ar[1]. I do not want to iterate through a loop

So I tried

Encoding.UTF8.GetBytes(ar[0]) 

and it returns

System.byte[]

How do i convert it to the original ASCII knowing that this return just a byte array.

Charles Burns
  • 10,310
  • 7
  • 64
  • 81
abc abc
  • 3
  • 2
  • 3
  • just cast it to a char, or use the Encoding namespace https://stackoverflow.com/questions/5431004/convert-byte-to-char – Sebastian L May 24 '17 at 07:58
  • cool, my other question is is it possible to compare two words and see which word comes before what. Say for example, I have two words "Stag" and "Stage". So I want to see if Stag come before Stage, get the ascii values and compare the difference – abc abc May 24 '17 at 08:12
  • What do you mean "ASCII value", are you aware that strings in .NET consists of unicode code points? And are you aware that when talking about ASCII values and unicode code points, you should only be talking about *individual characters*? Getting the "ASCII value" of a .NET *string* is thus relatively meaningless. Please clarify what you want to accomplish. – Lasse V. Karlsen May 24 '17 at 08:14
  • If you want to **order** the strings, just do `StringComparer.OneOfTheUnderlyingComparers.Compare(s1, s2)`, it will tell you `<0` if s1 comes before s2, `>0` if s1 comes after s2 and `==0` if s1 is equal to s2 according to the specified comparison. – Lasse V. Karlsen May 24 '17 at 08:15

2 Answers2

0

Maybe, I didn't understand you right, but what about this way:

            string TestStr = "TestStr";
        byte[] TestStrAscii = System.Text.ASCIIEncoding.ASCII.GetBytes(TestStr.ToCharArray());
        foreach(byte bt in TestStrAscii)
        {
            System.Console.WriteLine(bt.ToString());
        }

The foreach-loop is just used to check the output. It returns each Character from your string in ASCII-Code

CJens
  • 39
  • 8
0
String test = Encoding.ASCII.GetString(ar[]);
Kahn Kah
  • 1,389
  • 7
  • 24
  • 49
  • Please add some context as to why this code is the answer. – hardillb May 24 '17 at 09:09
  • What do you mean context? Because it works of course! – Kahn Kah May 24 '17 at 09:10
  • 1
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess May 24 '17 at 10:12