2007/10/23

Convert to/from ASCII code

Sometimes I need to convert char to/from ASCII code, and here I list all the ways I know to do this.

1.Cast
int i = (int)'a';  //i = 97

2.System.Text.Encoding
/* Get the corresponding ASCII codes */
byte[] ByteArray = Encoding.ASCII.GetBytes(string)

/* Get the corresponding chars */
char[] CharArray = Encoding.ASCII.GetChars(byte[])

3.Convert.ToXXX()
char c = 'a';
int i = Convert.ToByte(c); //i = 97
int i = 98;
char c = Convert.ToChar(i); //c = 'b'

No comments:

Post a Comment