Encoding.ASCII 속성

정의

ASCII(7비트) 문자 집합에 대한 인코딩을 가져옵니다.

public:
 static property System::Text::Encoding ^ ASCII { System::Text::Encoding ^ get(); };
public static System.Text.Encoding ASCII { get; }
member this.ASCII : System.Text.Encoding
Public Shared ReadOnly Property ASCII As Encoding

속성 값

Encoding

ASCII(7비트) 문자 집합에 대한 인코딩입니다.

예제

다음 예제에서는 ascii 범위 밖에 있는 문자에 대 한 ASCII 인코딩의 영향을 보여 줍니다.

using namespace System;
using namespace System::Text;
using namespace System::Collections;
int main()
{
   
   // Create an ASCII encoding.
   Encoding^ ascii = Encoding::ASCII;
   
   // A Unicode String* with two characters outside the ASCII code range.
   String^ unicodeString = L"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 the positions of the special characters for later reference.
   int indexOfPi = unicodeString->IndexOf( L'\u03a0' );
   int indexOfSigma = unicodeString->IndexOf( L'\u03a3' );
   
   // Encode the String*.
   array<Byte>^encodedBytes = ascii->GetBytes( unicodeString );
   Console::WriteLine();
   Console::WriteLine( "Encoded bytes:" );
   IEnumerator^ myEnum = encodedBytes->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Byte b = safe_cast<Byte>(myEnum->Current);
      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 the missing Pi and Sigma characters.
   String^ decodedString = ascii->GetString( encodedBytes );
   Console::WriteLine();
   Console::WriteLine( "Decoded bytes:" );
   Console::WriteLine( decodedString );
}

/*
This code produces the following output.

Original string:
This unicode string contains two characters with codes outside the ASCII code range, Pi (Π) and Sigma (Σ).

Encoded bytes:
[84][104][105][115][32][117][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][100][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][105][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 range, Pi (?) and Sigma (?).

*/
using System;
using System.Text;

class EncodingExample 
{
  public static void Main() 
  {
      // Create an ASCII encoding.
      Encoding ascii = Encoding.ASCII;
  
      // 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 the positions of the special characters for later reference.
      int indexOfPi = unicodeString.IndexOf('\u03a0');
      int indexOfSigma = unicodeString.IndexOf('\u03a3');

      // Encode the 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 a string.
      // Notice missing the Pi and Sigma characters.
      String decodedString = ascii.GetString(encodedBytes);
      Console.WriteLine();
      Console.WriteLine("Decoded bytes:");
      Console.WriteLine(decodedString);
  }
}
/*
This code produces the following output.

Original string:
This unicode string contains two characters with codes outside the ASCII code range, Pi (Π) and Sigma (Σ).

Encoded bytes:
[84][104][105][115][32][117][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][100][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][105][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 range, Pi (?) and Sigma (?).

*/
Imports System.Text

Class EncodingExample
  Public Shared Sub Main()
      ' Create and ASCII encoding.
      Dim ascii As Encoding = Encoding.ASCII

      ' A Unicode string with two characters outside the ASCII code range.
      Dim unicodeString As String = "This unicode string contains two characters " + "with codes outside the ASCII code range, " + "Pi (" & ChrW(&H03A0) & ") and Sigma (" & ChrW(&H03A3) & ")."
      Console.WriteLine("Original string:")
      Console.WriteLine(unicodeString)

      ' Save the positions of the special characters for later reference.
      Dim indexOfPi As Integer = unicodeString.IndexOf(ChrW(&H03A0))
      Dim indexOfSigma As Integer = unicodeString.IndexOf(ChrW(&H03A3))

      ' Encode the string.
      Dim encodedBytes As Byte() = ascii.GetBytes(unicodeString)
      Console.WriteLine()
      Console.WriteLine("Encoded bytes:")
      For Each b In encodedBytes
          Console.Write("[{0}]", b)
      Next 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 a string.
      ' Notice missing Pi and Sigma characters.
      Dim decodedString As String = ascii.GetString(encodedBytes)
      Console.WriteLine()
      Console.WriteLine("Decoded bytes:")
      Console.WriteLine(decodedString)
  End Sub
End Class
'This code produces the following output.
'Original string:
'This unicode string contains two characters with codes outside the ASCII code range, Pi (Π) and Sigma (Σ).
'
'Encoded bytes:
'[84][104][105][115][32][117][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]'[100][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][105][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 range, Pi (?) and Sigma (?).
'

설명

ASCII 문자는 U + 0000에서 U + 007F 사이의 까지의 가장 낮은 128 유니코드 문자로 제한 됩니다.

앱에 대 한 ASCII 인코딩을 선택 하는 경우 다음 사항을 고려 하세요.

  • ASCII 인코딩은 일반적으로 ASCII가 필요한 프로토콜에 적합 합니다.

  • 8 비트 인코딩 (간혹 "ASCII"로 잘못 참조 됨)이 필요한 경우 ASCII 인코딩에 대해 UTF-8 인코딩을 권장 합니다. 0부터 7F 까지의 문자에 대해서는 결과가 동일 하지만 u t f-8을 사용 하면 표현할 수 있는 모든 유니코드 문자를 표현 하 여 데이터 손실을 방지할 수 있습니다. ASCII 인코딩에는 악의적 사용을 허용할 수 있는 8 번째 비트 모호성이 있지만 UTF-8 인코딩은 8 번째 비트를 명확 하 게 제거 합니다.

  • .NET Framework 버전 2.0 이전에는 8 번째 비트를 무시 하 여 스푸핑을 허용 .NET Framework. .NET Framework 2.0부터 ASCII가 아닌 코드 포인트가 디코딩하는 동안 대체 됩니다.

ASCIIEncoding이 속성에서 반환 되는 개체에는 앱에 대 한 적절 한 동작이 없을 수 있습니다. 대체 대체 (fallback)를 사용 하 여 인코딩할 수 없는 각 문자열과 물음표 ("?") 문자를 사용 하 여 디코딩할 수 없는 각 바이트를 바꿉니다. 대신, GetEncoding(String, EncoderFallback, DecoderFallback) ASCIIEncoding EncoderFallbackException DecoderFallbackException 다음 예제와 같이 메서드를 호출 하 여 대체 (fallback)가 있는 개체를 인스턴스화할 수 있습니다.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      Encoding enc = Encoding.GetEncoding("us-ascii", 
                                          new EncoderExceptionFallback(),
                                          new DecoderExceptionFallback());
      string value = "\u00C4 \u00F6 \u00AE"; 
      
      try {
         byte[] bytes= enc.GetBytes(value);
         foreach (var byt in bytes)
            Console.Write("{0:X2} ", byt);
         Console.WriteLine();

         string value2 = enc.GetString(bytes);
         Console.WriteLine(value2);
      }
      catch (EncoderFallbackException e) {
         Console.WriteLine("Unable to encode {0} at index {1}", 
                           e.IsUnknownSurrogate() ? 
                              String.Format("U+{0:X4} U+{1:X4}", 
                                            Convert.ToUInt16(e.CharUnknownHigh),
                                            Convert.ToUInt16(e.CharUnknownLow)) :
                              String.Format("U+{0:X4}", 
                                            Convert.ToUInt16(e.CharUnknown)),
                           e.Index);
      }
   }
}
// The example displays the following output:
//        Unable to encode U+00C4 at index 0
Imports System.Text

Module Example
   Public Sub Main()
      Dim enc As Encoding = Encoding.GetEncoding("us-ascii", 
                                                 New EncoderExceptionFallback(),
                                                 New DecoderExceptionFallback())
      Dim value As String = String.Format("{0} {1} {2}", 
                            ChrW(&h00C4), ChrW(&h00F6), ChrW(&h00AE))
      
      Try
         Dim bytes() As Byte = enc.GetBytes(value)
         For Each byt As Byte In bytes
            Console.Write("{0:X2} ", byt)
         Next       
         Console.WriteLine()
         Dim value2 As String = enc.GetString(bytes)
         Console.WriteLine(value2)
      Catch e As EncoderFallbackException
         Console.WriteLine("Unable to encode {0} at index {1}", 
                           If(e.IsUnknownSurrogate(), 
                              String.Format("U+{0:X4} U+{1:X4}", 
                                            Convert.ToUInt16(e.CharUnknownHigh),
                                            Convert.ToUInt16(e.CharUnknownLow)),
                              String.Format("U+{0:X4}", 
                                            Convert.ToUInt16(e.CharUnknown))),
                           e.Index)
      End Try
   End Sub
End Module
' The example displays the following output:
'       Unable to encode U+00C4 at index 0

적용 대상

추가 정보