Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to convert string/char to ascii values

I need to convert char to hex values. Refer to the Ascii table but I have a few examples listed below:

  • char 1 = 31 2 = 32 3 = 33 4 = 34 5 = 35 A = 41 a = 61 etc

Therefore string str = "12345"; Need to get the converted str = "3132333435"

like image 689
SA. Avatar asked Apr 24 '10 02:04

SA.


People also ask

How do I get the ASCII code for a string?

ASCII value of a String is the Sum of ASCII values of all characters of a String. Step 1: Loop through all characters of a string using a FOR loop or any other loop. Step 3: Now add all the ASCII values of all characters to get the final ASCII value.

How do I get the ASCII value of a character?

Here are few methods in different programming languages to print ASCII value of a given character : Python code using ord function : ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord('a') returns the integer 97.

How do I get the ASCII value of a string in Python?

To get ascii value of char python, the ord () method is used. It is in-built in the library of character methods provided by Python. ASCII or American Standard Code for Information Interchange is the numeric value that is given to different characters and symbols.

How do I convert Word to ASCII?

Open the document to export. Click File > Export. In the Export dialog box, click ASCII Text in the Save as type list. In the File Name box, either create a new file by typing a name and extension, or replace data in an existing file with the exported data by selecting the file.


3 Answers

I think this is all you'll need:

string finalValue;
byte[] ascii = Encoding.ASCII.GetBytes(yourString);
foreach (Byte b in ascii) 
{
  finalValue += b.ToString("X");
}

More info on MSDN: http://msdn.microsoft.com/en-us/library/system.text.encoding.ascii.aspx

Edit: To Hex:

string finalValue;
int value;
foreach (char c in myString)
{
  value = Convert.ToInt32(c);
  finalValue += value.ToString("X"); 
  // or finalValue = String.Format("{0}{1:X}", finalValue, value);
}
// use finalValue
like image 145
Jim Schubert Avatar answered Oct 19 '22 08:10

Jim Schubert


string.Join("", from c in "12345" select ((int)c).ToString("X"));
like image 36
Matthew Flaschen Avatar answered Oct 19 '22 07:10

Matthew Flaschen


string s = "abc123";
foreach(char c in s)
{
   Response.Write((int)c + ",");
}
like image 35
G.M. Patel Avatar answered Oct 19 '22 07:10

G.M. Patel