本文整理汇总了C#中System.Text.ASCIIEncoding类的典型用法代码示例。如果您正苦于以下问题:C# ASCIIEncoding类的具体用法?C# ASCIIEncoding怎么用?C# ASCIIEncoding使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ASCIIEncoding类属于System.Text命名空间,在下文中一共展示了ASCIIEncoding类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Text;
class ASCIIEncodingExample {
public static void Main() {
// The encoding.
ASCIIEncoding ascii = new ASCIIEncoding();
// A Unicode string with two characters outside the ASCII code range.
String unicodeString =
"This Unicode string contains two characters " +
"with codes outside the ASCII code range, " +
"Pi (\u03a0) and Sigma (\u03a3).";
Console.WriteLine("Original string:");
Console.WriteLine(unicodeString);
// Save positions of the special characters for later reference.
int indexOfPi = unicodeString.IndexOf('\u03a0');
int indexOfSigma = unicodeString.IndexOf('\u03a3');
// Encode string.
Byte[] encodedBytes = ascii.GetBytes(unicodeString);
Console.WriteLine();
Console.WriteLine("Encoded bytes:");
foreach (Byte b in encodedBytes) {
Console.Write("[{0}]", b);
}
Console.WriteLine();
// Notice that the special characters have been replaced with
// the value 63, which is the ASCII character code for '?'.
Console.WriteLine();
Console.WriteLine(
"Value at position of Pi character: {0}",
encodedBytes[indexOfPi]
);
Console.WriteLine(
"Value at position of Sigma character: {0}",
encodedBytes[indexOfSigma]
);
// Decode bytes back to string.
// Notice missing Pi and Sigma characters.
String decodedString = ascii.GetString(encodedBytes);
Console.WriteLine();
Console.WriteLine("Decoded bytes:");
Console.WriteLine(decodedString);
}
}
输出:
Original string: This Unicode string contains two characters with codes outside the ASCII code ra nge, Pi (Π) and Sigma (Σ). Encoded bytes: [84][104][105][115][32][85][110][105][99][111][100][101][32][115][116][114][105] [110][103][32][99][111][110][116][97][105][110][115][32][116][119][111][32][99][ 104][97][114][97][99][116][101][114][115][32][119][105][116][104][32][99][111][1 00][101][115][32][111][117][116][115][105][100][101][32][116][104][101][32][65][ 83][67][73][73][32][99][111][100][101][32][114][97][110][103][101][44][32][80][1 05][32][40][63][41][32][97][110][100][32][83][105][103][109][97][32][40][63][41] [46] Value at position of Pi character: 63 Value at position of Sigma character: 63 Decoded bytes: This Unicode string contains two characters with codes outside the ASCII code ra nge, Pi (?) and Sigma (?).
示例2: new ASCIIEncoding
//引入命名空间
using System;
using System.Text;
class StringEncodingApp {
static void Main(string[] args) {
ASCIIEncoding ae = new ASCIIEncoding();
Console.WriteLine(ae.GetString(new byte[]{1,2,3}));
UnicodeEncoding bu = new UnicodeEncoding(true, false);
Console.WriteLine(bu.GetString(new byte[]{1,2,3}));
}
}