6

I want to get the decimal ASCII value of a string in C#, for instance:

"abc123s" would be: 97 98 99 49 50 51 115 (979899495051115) 'f1c3s1"would be:102 49 99 51 115 49or1024999511549`

I tried Convert.ToInt32 or Int.Parse but they do not result in the desired effect.

What method can I use for this?

pb2q
  • 58,613
  • 19
  • 146
  • 147
user1760791
  • 403
  • 3
  • 12
  • 1
    Check this out: http://stackoverflow.com/questions/400733/how-to-get-ascii-value-of-string-in-c-sharp – d4Rk Jun 06 '15 at 13:46
  • 1
    string input = "I want to get the decimal ASCII value of a string in C#, for instance"; byte[] array = Encoding.UTF8.GetBytes(input); – jdweng Jun 06 '15 at 13:49
  • Strings in C# are Unicode, not ASCII. If all your characters are in the ASCII character set, then you can just use the Unicode character code as it is a subset of ASCII. Then you just convert each `char` value to `int`. The `Convert.ToInt32` works fine for that if you use it on each character, not on the whole string. – Guffa Jun 06 '15 at 13:52

3 Answers3

6

Assuming that you're only working with ASCII strings, you can cast each character of the string to a byte to get the ASCII representation. You can roll the results back into a string using ToString on the values:

string str = "abc123s";
string outStr = String.Empty;

foreach (char c in str)
    outStr += ((byte) c).ToString();

You could also get the byte values as an array, and make the results into a string using String.Join:

byte[] asciiVals = System.Text.Encoding.ASCII.GetBytes(str);
outStr = String.Join(String.Empty, asciiVals);
pb2q
  • 58,613
  • 19
  • 146
  • 147
1

Try

string all = "";

all = String.Join(String.Empty, "abc123s".Select(c => ((int)c).ToString()).ToArray());
artm
  • 8,554
  • 3
  • 26
  • 43
0

you could use Convert.ToInt16() in combination with a loop for each character and add the int Results as string together.

You shouldn't use Byte because every Char is a Int16.

leAthlon
  • 734
  • 1
  • 10
  • 22