Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get numeric value of all characters in a string [duplicate]

Tags:

c#

ascii

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?

like image 527
user1760791 Avatar asked Jun 06 '15 13:06

user1760791


People also ask

Can you write code for finding all duplicate characters in string?

String str = "beautiful beach"; char[] carray = str. toCharArray(); System. out. println("The string is:" + str);


2 Answers

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);
like image 143
pb2q Avatar answered Oct 12 '22 17:10

pb2q


Try

string all = "";

all = String.Join(String.Empty, "abc123s".Select(c => ((int)c).ToString()).ToArray());
like image 29
artm Avatar answered Oct 12 '22 19:10

artm