Encoding.GetBytes 메서드

정의

파생 클래스에서 재정의되면 문자 집합을 바이트 시퀀스로 인코딩합니다.

오버로드

GetBytes(Char[])

파생 클래스에서 재정의되면 지정한 문자 배열의 모든 문자를 바이트 시퀀스로 인코딩합니다.

GetBytes(String)

파생 클래스에서 재정의되면 지정한 문자열의 모든 문자를 바이트 시퀀스로 인코딩합니다.

GetBytes(ReadOnlySpan<Char>, Span<Byte>)

파생 클래스에서 재정의할 경우, 지정된 읽기 전용 범위의 문자 집합을 바이트 범위로 인코딩합니다.

GetBytes(Char[], Int32, Int32)

파생 클래스에서 재정의되면 지정한 문자 배열의 문자 집합을 바이트 시퀀스로 인코딩합니다.

GetBytes(String, Int32, Int32)

파생 클래스에서 재정의할 경우, 지정된 index에서 시작하여 지정한 문자열 내에서 count로 지정된 문자의 수를 바이트 배결로 인코딩합니다.

GetBytes(Char*, Int32, Byte*, Int32)

파생 클래스에서 재정의되면 지정한 문자 포인터에서 시작하는 문자 집합을 지정한 바이트 포인터에서 시작하여 저장되는 바이트 시퀀스로 인코딩합니다.

GetBytes(Char[], Int32, Int32, Byte[], Int32)

파생 클래스에서 재정의되면 지정한 문자 배열의 문자 집합을 지정한 바이트 배열로 인코딩합니다.

GetBytes(String, Int32, Int32, Byte[], Int32)

파생 클래스에서 재정의되면 지정한 문자열의 문자 집합을 지정한 바이트 배열로 인코딩합니다.

GetBytes(Char[])

파생 클래스에서 재정의되면 지정한 문자 배열의 모든 문자를 바이트 시퀀스로 인코딩합니다.

public:
 virtual cli::array <System::Byte> ^ GetBytes(cli::array <char> ^ chars);
public virtual byte[] GetBytes (char[] chars);
abstract member GetBytes : char[] -> byte[]
override this.GetBytes : char[] -> byte[]
Public Overridable Function GetBytes (chars As Char()) As Byte()

매개 변수

chars
Char[]

인코딩할 문자가 포함된 문자 배열입니다.

반환

Byte[]

지정한 문자 집합을 인코딩한 결과가 포함된 바이트 배열입니다.

예외

chars이(가) null인 경우

대체가 발생했습니다(자세한 내용은 .NET의 문자 인코딩 참조).

EncoderFallbackEncoderExceptionFallback로 설정됩니다.

예제

다음 예에서는 문자 배열을 인코딩하고 문자를 인코딩하고 결과 바이트를 표시 하는 데 필요한 바이트 수를 결정 합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndBytes( array<Char>^chars, Encoding^ enc );
void PrintHexBytes( array<Byte>^bytes );
int main()
{
   
   // The characters to encode:
   //    Latin Small Letter Z (U+007A)
   //    Latin Small Letter A (U+0061)
   //    Combining Breve (U+0306)
   //    Latin Small Letter AE With Acute (U+01FD)
   //    Greek Small Letter Beta (U+03B2)
   //    a high-surrogate value (U+D8FF)
   //    a low-surrogate value (U+DCFF)
   array<Char>^myChars = gcnew array<Char>{
      L'z','a',L'\u0306',L'\u01FD',L'\u03B2',L'\xD8FF',L'\xDCFF'
   };
   
   // Get different encodings.
   Encoding^ u7 = Encoding::UTF7;
   Encoding^ u8 = Encoding::UTF8;
   Encoding^ u16LE = Encoding::Unicode;
   Encoding^ u16BE = Encoding::BigEndianUnicode;
   Encoding^ u32 = Encoding::UTF32;
   
   // Encode the entire array, and print out the counts and the resulting bytes.
   PrintCountsAndBytes( myChars, u7 );
   PrintCountsAndBytes( myChars, u8 );
   PrintCountsAndBytes( myChars, u16LE );
   PrintCountsAndBytes( myChars, u16BE );
   PrintCountsAndBytes( myChars, u32 );
}

void PrintCountsAndBytes( array<Char>^chars, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( chars );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( chars->Length );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode the array of chars.
   array<Byte>^bytes = enc->GetBytes( chars );
   
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintHexBytes( array<Byte>^bytes )
{
   if ( (bytes == nullptr) || (bytes->Length == 0) )
      Console::WriteLine( "<none>" );
   else
   {
      for ( int i = 0; i < bytes->Length; i++ )
         Console::Write( "{0:X2} ", bytes[ i ] );
      Console::WriteLine();
   }
}

/* 
This code produces the following output.

System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // The characters to encode:
      //    Latin Small Letter Z (U+007A)
      //    Latin Small Letter A (U+0061)
      //    Combining Breve (U+0306)
      //    Latin Small Letter AE With Acute (U+01FD)
      //    Greek Small Letter Beta (U+03B2)
      //    a high-surrogate value (U+D8FF)
      //    a low-surrogate value (U+DCFF)
      char[] myChars = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };

      // Get different encodings.
      Encoding  u7    = Encoding.UTF7;
      Encoding  u8    = Encoding.UTF8;
      Encoding  u16LE = Encoding.Unicode;
      Encoding  u16BE = Encoding.BigEndianUnicode;
      Encoding  u32   = Encoding.UTF32;

      // Encode the entire array, and print out the counts and the resulting bytes.
      PrintCountsAndBytes( myChars, u7 );
      PrintCountsAndBytes( myChars, u8 );
      PrintCountsAndBytes( myChars, u16LE );
      PrintCountsAndBytes( myChars, u16BE );
      PrintCountsAndBytes( myChars, u32 );
   }

   public static void PrintCountsAndBytes( char[] chars, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( chars );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( chars.Length );
      Console.Write( " {0,-3} :", iMBC );

      // Encode the array of chars.
      byte[] bytes = enc.GetBytes( chars );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintHexBytes( byte[] bytes )  {

      if (( bytes == null ) || ( bytes.Length == 0 ))
        {
            Console.WriteLine( "<none>" );
        }
        else  {
         for ( int i = 0; i < bytes.Length; i++ )
            Console.Write( "{0:X2} ", bytes[i] );
         Console.WriteLine();
      }
   }
}


/* 
This code produces the following output.

System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' The characters to encode:
      '    Latin Small Letter Z (U+007A)
      '    Latin Small Letter A (U+0061)
      '    Combining Breve (U+0306)
      '    Latin Small Letter AE With Acute (U+01FD)
      '    Greek Small Letter Beta (U+03B2)
      '    a high-surrogate value (U+D8FF)
      '    a low-surrogate value (U+DCFF)
      Dim myChars() As Char = {"z"c, "a"c, ChrW(&H0306), ChrW(&H01FD), ChrW(&H03B2), ChrW(&HD8FF), ChrW(&HDCFF)}
 

      ' Get different encodings.
      Dim u7 As Encoding = Encoding.UTF7
      Dim u8 As Encoding = Encoding.UTF8
      Dim u16LE As Encoding = Encoding.Unicode
      Dim u16BE As Encoding = Encoding.BigEndianUnicode
      Dim u32 As Encoding = Encoding.UTF32

      ' Encode the entire array, and print out the counts and the resulting bytes.
      PrintCountsAndBytes(myChars, u7)
      PrintCountsAndBytes(myChars, u8)
      PrintCountsAndBytes(myChars, u16LE)
      PrintCountsAndBytes(myChars, u16BE)
      PrintCountsAndBytes(myChars, u32)

   End Sub


   Public Shared Sub PrintCountsAndBytes(chars() As Char, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(chars)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(chars.Length)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode the array of chars.
      Dim bytes As Byte() = enc.GetBytes(chars)

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Public Shared Sub PrintHexBytes(bytes() As Byte)

      If bytes Is Nothing OrElse bytes.Length = 0 Then
         Console.WriteLine("<none>")
      Else
         Dim i As Integer
         For i = 0 To bytes.Length - 1
            Console.Write("{0:X2} ", bytes(i))
         Next i
         Console.WriteLine()
      End If

   End Sub

End Class


'This code produces the following output.
'
'System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
'System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

설명

변환 되는 데이터를 순차 블록 에서만 사용할 수 있는 경우 (예: 스트림에서 읽은 데이터) 또는 데이터 양이 작은 블록으로 분할 해야 하는 경우에는 Decoder 메서드 또는 메서드에서 제공 하는 또는를 Encoder 파생 된 GetDecoder GetEncoder 클래스의 각 메서드에서 사용 해야 합니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우에는 메서드의 문자열 버전을 호출 해야 합니다 GetBytes .

  • 의 유니코드 문자 버퍼 버전에서는 GetBytes(Char*, Int32, Byte*, Int32) 특히 개체를 사용 Encoder 하거나 기존 버퍼에 삽입 하는 여러 호출을 통해 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

추가 정보

적용 대상

GetBytes(String)

파생 클래스에서 재정의되면 지정한 문자열의 모든 문자를 바이트 시퀀스로 인코딩합니다.

public:
 virtual cli::array <System::Byte> ^ GetBytes(System::String ^ s);
public virtual byte[] GetBytes (string s);
abstract member GetBytes : string -> byte[]
override this.GetBytes : string -> byte[]
Public Overridable Function GetBytes (s As String) As Byte()

매개 변수

s
String

인코딩할 문자가 포함된 문자열입니다.

반환

Byte[]

지정한 문자 집합을 인코딩한 결과가 포함된 바이트 배열입니다.

예외

s이(가) null인 경우

대체가 발생했습니다(자세한 내용은 .NET의 문자 인코딩 참조).

EncoderFallbackEncoderExceptionFallback로 설정됩니다.

예제

다음 예에서는 문자열 또는 문자열의 범위를 인코딩하고 문자를 인코딩하고 결과 바이트를 표시 하는 데 필요한 바이트 수를 결정 합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndBytes( String^ s, Encoding^ enc );
void PrintCountsAndBytes( String^ s, int index, int count, Encoding^ enc );
void PrintHexBytes( array<Byte>^bytes );
int main()
{
   
   // The characters to encode:
   //    Latin Small Letter Z (U+007A)
   //    Latin Small Letter A (U+0061)
   //    Combining Breve (U+0306)
   //    Latin Small Letter AE With Acute (U+01FD)
   //    Greek Small Letter Beta (U+03B2)
   //    a high-surrogate value (U+D8FF)
   //    a low-surrogate value (U+DCFF)
   String^ myStr = L"za\u0306\u01FD\u03B2\xD8FF\xDCFF";
   
   // Get different encodings.
   Encoding^ u7 = Encoding::UTF7;
   Encoding^ u8 = Encoding::UTF8;
   Encoding^ u16LE = Encoding::Unicode;
   Encoding^ u16BE = Encoding::BigEndianUnicode;
   Encoding^ u32 = Encoding::UTF32;
   
   // Encode the entire string, and print out the counts and the resulting bytes.
   Console::WriteLine( "Encoding the entire string:" );
   PrintCountsAndBytes( myStr, u7 );
   PrintCountsAndBytes( myStr, u8 );
   PrintCountsAndBytes( myStr, u16LE );
   PrintCountsAndBytes( myStr, u16BE );
   PrintCountsAndBytes( myStr, u32 );
   Console::WriteLine();
   
   // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
   Console::WriteLine( "Encoding the characters from index 4 through 6:" );
   PrintCountsAndBytes( myStr, 4, 3, u7 );
   PrintCountsAndBytes( myStr, 4, 3, u8 );
   PrintCountsAndBytes( myStr, 4, 3, u16LE );
   PrintCountsAndBytes( myStr, 4, 3, u16BE );
   PrintCountsAndBytes( myStr, 4, 3, u32 );
}

void PrintCountsAndBytes( String^ s, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( s );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( s->Length );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode the entire string.
   array<Byte>^bytes = enc->GetBytes( s );
   
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintCountsAndBytes( String^ s, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( s->ToCharArray(), index, count );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( count );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode a range of characters in the string.
   array<Byte>^bytes = gcnew array<Byte>(iBC);
   enc->GetBytes( s, index, count, bytes, bytes->GetLowerBound( 0 ) );
   
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintHexBytes( array<Byte>^bytes )
{
   if ( (bytes == nullptr) || (bytes->Length == 0) )
      Console::WriteLine( "<none>" );
   else
   {
      for ( int i = 0; i < bytes->Length; i++ )
         Console::Write( "{0:X2} ", bytes[ i ] );
      Console::WriteLine();
   }
}

/* 
This code produces the following output.

Encoding the entire string:
System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

Encoding the characters from index 4 through 6:
System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // The characters to encode:
      //    Latin Small Letter Z (U+007A)
      //    Latin Small Letter A (U+0061)
      //    Combining Breve (U+0306)
      //    Latin Small Letter AE With Acute (U+01FD)
      //    Greek Small Letter Beta (U+03B2)
      //    a high-surrogate value (U+D8FF)
      //    a low-surrogate value (U+DCFF)
      String myStr = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";

      // Get different encodings.
      Encoding  u7    = Encoding.UTF7;
      Encoding  u8    = Encoding.UTF8;
      Encoding  u16LE = Encoding.Unicode;
      Encoding  u16BE = Encoding.BigEndianUnicode;
      Encoding  u32   = Encoding.UTF32;

      // Encode the entire string, and print out the counts and the resulting bytes.
      Console.WriteLine( "Encoding the entire string:" );
      PrintCountsAndBytes( myStr, u7 );
      PrintCountsAndBytes( myStr, u8 );
      PrintCountsAndBytes( myStr, u16LE );
      PrintCountsAndBytes( myStr, u16BE );
      PrintCountsAndBytes( myStr, u32 );

      Console.WriteLine();

      // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      Console.WriteLine( "Encoding the characters from index 4 through 6:" );
      PrintCountsAndBytes( myStr, 4, 3, u7 );
      PrintCountsAndBytes( myStr, 4, 3, u8 );
      PrintCountsAndBytes( myStr, 4, 3, u16LE );
      PrintCountsAndBytes( myStr, 4, 3, u16BE );
      PrintCountsAndBytes( myStr, 4, 3, u32 );
   }

   public static void PrintCountsAndBytes( String s, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( s );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( s.Length );
      Console.Write( " {0,-3} :", iMBC );

      // Encode the entire string.
      byte[] bytes = enc.GetBytes( s );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintCountsAndBytes( String s, int index, int count, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( s.ToCharArray(), index, count );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( count );
      Console.Write( " {0,-3} :", iMBC );

      // Encode a range of characters in the string.
      byte[] bytes = new byte[iBC];
      enc.GetBytes( s, index, count, bytes, bytes.GetLowerBound(0) );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintHexBytes( byte[] bytes )  {

      if (( bytes == null ) || ( bytes.Length == 0 ))
        {
            Console.WriteLine( "<none>" );
        }
        else  {
         for ( int i = 0; i < bytes.Length; i++ )
            Console.Write( "{0:X2} ", bytes[i] );
         Console.WriteLine();
      }
   }
}


/* 
This code produces the following output.

Encoding the entire string:
System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

Encoding the characters from index 4 through 6:
System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' The characters to encode:
      '    Latin Small Letter Z (U+007A)
      '    Latin Small Letter A (U+0061)
      '    Combining Breve (U+0306)
      '    Latin Small Letter AE With Acute (U+01FD)
      '    Greek Small Letter Beta (U+03B2)
      '    a high-surrogate value (U+D8FF)
      '    a low-surrogate value (U+DCFF)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2) & ChrW(&HD8FF) & ChrW(&HDCFF)

      ' Get different encodings.
      Dim u7 As Encoding = Encoding.UTF7
      Dim u8 As Encoding = Encoding.UTF8
      Dim u16LE As Encoding = Encoding.Unicode
      Dim u16BE As Encoding = Encoding.BigEndianUnicode
      Dim u32 As Encoding = Encoding.UTF32

      ' Encode the entire string, and print out the counts and the resulting bytes.
      Console.WriteLine("Encoding the entire string:")
      PrintCountsAndBytes(myStr, u7)
      PrintCountsAndBytes(myStr, u8)
      PrintCountsAndBytes(myStr, u16LE)
      PrintCountsAndBytes(myStr, u16BE)
      PrintCountsAndBytes(myStr, u32)

      Console.WriteLine()

      ' Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      Console.WriteLine("Encoding the characters from index 4 through 6:")
      PrintCountsAndBytes(myStr, 4, 3, u7)
      PrintCountsAndBytes(myStr, 4, 3, u8)
      PrintCountsAndBytes(myStr, 4, 3, u16LE)
      PrintCountsAndBytes(myStr, 4, 3, u16BE)
      PrintCountsAndBytes(myStr, 4, 3, u32)

   End Sub


   Overloads Public Shared Sub PrintCountsAndBytes(s As String, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(s)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(s.Length)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode the entire string.
      Dim bytes As Byte() = enc.GetBytes(s)

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Overloads Public Shared Sub PrintCountsAndBytes(s As String, index As Integer, count As Integer, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(s.ToCharArray(), index, count)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(count)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode a range of characters in the string.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      Dim bytes(iBC - 1) As Byte
      enc.GetBytes(s, index, count, bytes, bytes.GetLowerBound(0))

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Public Shared Sub PrintHexBytes(bytes() As Byte)

      If bytes Is Nothing OrElse bytes.Length = 0 Then
         Console.WriteLine("<none>")
      Else
         Dim i As Integer
         For i = 0 To bytes.Length - 1
            Console.Write("{0:X2} ", bytes(i))
         Next i
         Console.WriteLine()
      End If

   End Sub

End Class


'This code produces the following output.
'
'Encoding the entire string:
'System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
'System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00
'
'Encoding the characters from index 4 through 6:
'System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
'System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

설명

변환 되는 데이터를 순차 블록 에서만 사용할 수 있는 경우 (예: 스트림에서 읽은 데이터) 또는 데이터 양이 작은 블록으로 분할 해야 하는 경우에는 Decoder 메서드 또는 메서드에서 제공 하는 또는를 Encoder 파생 된 GetDecoder GetEncoder 클래스의 각 메서드에서 사용 해야 합니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. Encoding.GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우의 문자열 버전을 사용 해야 합니다 GetBytes .

  • 의 유니코드 문자 버퍼 버전에서는 GetBytes(Char*, Int32, Byte*, Int32) 특히 개체를 사용 Encoder 하거나 기존 버퍼에 삽입 하는 여러 호출을 통해 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

추가 정보

적용 대상

GetBytes(ReadOnlySpan<Char>, Span<Byte>)

파생 클래스에서 재정의할 경우, 지정된 읽기 전용 범위의 문자 집합을 바이트 범위로 인코딩합니다.

public:
 virtual int GetBytes(ReadOnlySpan<char> chars, Span<System::Byte> bytes);
public virtual int GetBytes (ReadOnlySpan<char> chars, Span<byte> bytes);
abstract member GetBytes : ReadOnlySpan<char> * Span<byte> -> int
override this.GetBytes : ReadOnlySpan<char> * Span<byte> -> int
Public Overridable Function GetBytes (chars As ReadOnlySpan(Of Char), bytes As Span(Of Byte)) As Integer

매개 변수

chars
ReadOnlySpan<Char>

인코딩할 문자 집합을 포함하는 범위입니다.

bytes
Span<Byte>

인코딩된 바이트를 저장할 바이트 범위입니다.

반환

Int32

인코딩된 바이트 수입니다.

설명

변환 되는 데이터를 순차 블록 에서만 사용할 수 있는 경우 (예: 스트림에서 읽은 데이터) 또는 데이터 양이 작은 블록으로 분할 해야 하는 경우에는 Decoder 메서드 또는 메서드에서 제공 하는 또는를 Encoder 파생 된 GetDecoder GetEncoder 클래스의 각 메서드에서 사용 해야 합니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. Encoding.GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우의 문자열 버전을 사용 해야 합니다 GetBytes .

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

적용 대상

GetBytes(Char[], Int32, Int32)

파생 클래스에서 재정의되면 지정한 문자 배열의 문자 집합을 바이트 시퀀스로 인코딩합니다.

public:
 virtual cli::array <System::Byte> ^ GetBytes(cli::array <char> ^ chars, int index, int count);
public virtual byte[] GetBytes (char[] chars, int index, int count);
abstract member GetBytes : char[] * int * int -> byte[]
override this.GetBytes : char[] * int * int -> byte[]
Public Overridable Function GetBytes (chars As Char(), index As Integer, count As Integer) As Byte()

매개 변수

chars
Char[]

인코딩할 문자 집합이 포함된 문자 배열입니다.

index
Int32

인코딩할 첫 번째 문자의 인덱스입니다.

count
Int32

인코딩할 문자 수입니다.

반환

Byte[]

지정한 문자 집합을 인코딩한 결과가 포함된 바이트 배열입니다.

예외

chars이(가) null인 경우

index 또는 count가 0보다 작습니다.

또는

indexcountchars에서 올바른 범위를 나타내지 않습니다.

대체가 발생했습니다(자세한 내용은 .NET의 문자 인코딩 참조).

EncoderFallbackEncoderExceptionFallback로 설정됩니다.

예제

다음 예제에서는 문자 배열에서 3 개의 문자를 인코딩하고 문자를 인코딩하고 결과 바이트를 표시 하는 데 필요한 바이트 수를 결정 합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndBytes( array<Char>^chars, int index, int count, Encoding^ enc );
void PrintHexBytes( array<Byte>^bytes );
int main()
{
   
   // The characters to encode:
   //    Latin Small Letter Z (U+007A)
   //    Latin Small Letter A (U+0061)
   //    Combining Breve (U+0306)
   //    Latin Small Letter AE With Acute (U+01FD)
   //    Greek Small Letter Beta (U+03B2)
   //    a high-surrogate value (U+D8FF)
   //    a low-surrogate value (U+DCFF)
   array<Char>^myChars = gcnew array<Char>{
      L'z',L'a',L'\u0306',L'\u01FD',L'\u03B2',L'\xD8FF',L'\xDCFF'
   };
   
   // Get different encodings.
   Encoding^ u7 = Encoding::UTF7;
   Encoding^ u8 = Encoding::UTF8;
   Encoding^ u16LE = Encoding::Unicode;
   Encoding^ u16BE = Encoding::BigEndianUnicode;
   Encoding^ u32 = Encoding::UTF32;
   
   // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
   PrintCountsAndBytes( myChars, 4, 3, u7 );
   PrintCountsAndBytes( myChars, 4, 3, u8 );
   PrintCountsAndBytes( myChars, 4, 3, u16LE );
   PrintCountsAndBytes( myChars, 4, 3, u16BE );
   PrintCountsAndBytes( myChars, 4, 3, u32 );
}

void PrintCountsAndBytes( array<Char>^chars, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( chars, index, count );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( count );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode the array of chars.
   array<Byte>^bytes = enc->GetBytes( chars, index, count );
   
   // The following is an alternative way to encode the array of chars:
   // byte[] bytes = new byte[iBC];
   // enc.GetBytes( chars, index, count, bytes, bytes.GetLowerBound(0) );
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintHexBytes( array<Byte>^bytes )
{
   if ( (bytes == nullptr) || (bytes->Length == 0) )
      Console::WriteLine( "<none>" );
   else
   {
      for ( int i = 0; i < bytes->Length; i++ )
         Console::Write( "{0:X2} ", bytes[ i ] );
      Console::WriteLine();
   }
}

/* 
This code produces the following output.

System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // The characters to encode:
      //    Latin Small Letter Z (U+007A)
      //    Latin Small Letter A (U+0061)
      //    Combining Breve (U+0306)
      //    Latin Small Letter AE With Acute (U+01FD)
      //    Greek Small Letter Beta (U+03B2)
      //    a high-surrogate value (U+D8FF)
      //    a low-surrogate value (U+DCFF)
      char[] myChars = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };

      // Get different encodings.
      Encoding  u7    = Encoding.UTF7;
      Encoding  u8    = Encoding.UTF8;
      Encoding  u16LE = Encoding.Unicode;
      Encoding  u16BE = Encoding.BigEndianUnicode;
      Encoding  u32   = Encoding.UTF32;

      // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      PrintCountsAndBytes( myChars, 4, 3, u7 );
      PrintCountsAndBytes( myChars, 4, 3, u8 );
      PrintCountsAndBytes( myChars, 4, 3, u16LE );
      PrintCountsAndBytes( myChars, 4, 3, u16BE );
      PrintCountsAndBytes( myChars, 4, 3, u32 );
   }

   public static void PrintCountsAndBytes( char[] chars, int index, int count, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( chars, index, count );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( count );
      Console.Write( " {0,-3} :", iMBC );

      // Encode the array of chars.
      byte[] bytes = enc.GetBytes( chars, index, count );

      // The following is an alternative way to encode the array of chars:
      // byte[] bytes = new byte[iBC];
      // enc.GetBytes( chars, index, count, bytes, bytes.GetLowerBound(0) );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintHexBytes( byte[] bytes )  {

      if (( bytes == null ) || ( bytes.Length == 0 ))
        {
            Console.WriteLine( "<none>" );
        }
        else  {
         for ( int i = 0; i < bytes.Length; i++ )
            Console.Write( "{0:X2} ", bytes[i] );
         Console.WriteLine();
      }
   }
}


/* 
This code produces the following output.

System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' The characters to encode:
      '    Latin Small Letter Z (U+007A)
      '    Latin Small Letter A (U+0061)
      '    Combining Breve (U+0306)
      '    Latin Small Letter AE With Acute (U+01FD)
      '    Greek Small Letter Beta (U+03B2)
      '    a high-surrogate value (U+D8FF)
      '    a low-surrogate value (U+DCFF)
      Dim myChars() As Char = {"z"c, "a"c, ChrW(&H0306), ChrW(&H01FD), ChrW(&H03B2), ChrW(&HD8FF), ChrW(&HDCFF) }

      ' Get different encodings.
      Dim u7 As Encoding = Encoding.UTF7
      Dim u8 As Encoding = Encoding.UTF8
      Dim u16LE As Encoding = Encoding.Unicode
      Dim u16BE As Encoding = Encoding.BigEndianUnicode
      Dim u32 As Encoding = Encoding.UTF32

      ' Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      PrintCountsAndBytes(myChars, 4, 3, u7)
      PrintCountsAndBytes(myChars, 4, 3, u8)
      PrintCountsAndBytes(myChars, 4, 3, u16LE)
      PrintCountsAndBytes(myChars, 4, 3, u16BE)
      PrintCountsAndBytes(myChars, 4, 3, u32)

   End Sub


   Public Shared Sub PrintCountsAndBytes(chars() As Char, index As Integer, count As Integer, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(chars, index, count)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(count)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode the array of chars.
      Dim bytes As Byte() = enc.GetBytes(chars, index, count)

      ' The following is an alternative way to encode the array of chars:
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      ' Dim bytes(iBC - 1) As Byte
      ' enc.GetBytes( chars, index, count, bytes, bytes.GetLowerBound(0) )

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Public Shared Sub PrintHexBytes(bytes() As Byte)

      If bytes Is Nothing OrElse bytes.Length = 0 Then
         Console.WriteLine("<none>")
      Else
         Dim i As Integer
         For i = 0 To bytes.Length - 1
            Console.Write("{0:X2} ", bytes(i))
         Next i
         Console.WriteLine()
      End If

   End Sub

End Class


'This code produces the following output.
'
'System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
'System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

설명

변환 되는 데이터를 순차 블록 에서만 사용할 수 있는 경우 (예: 스트림에서 읽은 데이터) 또는 데이터 양이 작은 블록으로 분할 해야 하는 경우에는 Decoder 메서드 또는 메서드에서 제공 하는 또는를 Encoder 파생 된 GetDecoder GetEncoder 클래스의 각 메서드에서 사용 해야 합니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. Encoding.GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우의 문자열 버전을 사용 해야 합니다 GetBytes .

  • 의 유니코드 문자 버퍼 버전에서는 GetBytes(Char*, Int32, Byte*, Int32) 특히 개체를 사용 Encoder 하거나 기존 버퍼에 삽입 하는 여러 호출을 통해 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

추가 정보

적용 대상

GetBytes(String, Int32, Int32)

파생 클래스에서 재정의할 경우, 지정된 index에서 시작하여 지정한 문자열 내에서 count로 지정된 문자의 수를 바이트 배결로 인코딩합니다.

public:
 cli::array <System::Byte> ^ GetBytes(System::String ^ s, int index, int count);
public byte[] GetBytes (string s, int index, int count);
member this.GetBytes : string * int * int -> byte[]
Public Function GetBytes (s As String, index As Integer, count As Integer) As Byte()

매개 변수

s
String

인코딩할 문자가 포함된 문자열입니다.

index
Int32

인코딩을 시작할 문자열 내의 인덱스입니다.

count
Int32

인코딩할 문자 수입니다.

반환

Byte[]

지정한 문자 집합을 인코딩한 결과가 포함된 바이트 배열입니다.

예제

다음 예에서는 문자열 또는 문자열의 범위를 인코딩하고 문자를 인코딩하고 결과 바이트를 표시 하는 데 필요한 바이트 수를 결정 합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndBytes( String^ s, Encoding^ enc );
void PrintCountsAndBytes( String^ s, int index, int count, Encoding^ enc );
void PrintHexBytes( array<Byte>^bytes );
int main()
{
   
   // The characters to encode:
   //    Latin Small Letter Z (U+007A)
   //    Latin Small Letter A (U+0061)
   //    Combining Breve (U+0306)
   //    Latin Small Letter AE With Acute (U+01FD)
   //    Greek Small Letter Beta (U+03B2)
   //    a high-surrogate value (U+D8FF)
   //    a low-surrogate value (U+DCFF)
   String^ myStr = L"za\u0306\u01FD\u03B2\xD8FF\xDCFF";
   
   // Get different encodings.
   Encoding^ u7 = Encoding::UTF7;
   Encoding^ u8 = Encoding::UTF8;
   Encoding^ u16LE = Encoding::Unicode;
   Encoding^ u16BE = Encoding::BigEndianUnicode;
   Encoding^ u32 = Encoding::UTF32;
   
   // Encode the entire string, and print out the counts and the resulting bytes.
   Console::WriteLine( "Encoding the entire string:" );
   PrintCountsAndBytes( myStr, u7 );
   PrintCountsAndBytes( myStr, u8 );
   PrintCountsAndBytes( myStr, u16LE );
   PrintCountsAndBytes( myStr, u16BE );
   PrintCountsAndBytes( myStr, u32 );
   Console::WriteLine();
   
   // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
   Console::WriteLine( "Encoding the characters from index 4 through 6:" );
   PrintCountsAndBytes( myStr, 4, 3, u7 );
   PrintCountsAndBytes( myStr, 4, 3, u8 );
   PrintCountsAndBytes( myStr, 4, 3, u16LE );
   PrintCountsAndBytes( myStr, 4, 3, u16BE );
   PrintCountsAndBytes( myStr, 4, 3, u32 );
}

void PrintCountsAndBytes( String^ s, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( s );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( s->Length );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode the entire string.
   array<Byte>^bytes = enc->GetBytes( s );
   
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintCountsAndBytes( String^ s, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( s->ToCharArray(), index, count );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( count );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode a range of characters in the string.
   array<Byte>^bytes = gcnew array<Byte>(iBC);
   enc->GetBytes( s, index, count, bytes, bytes->GetLowerBound( 0 ) );
   
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintHexBytes( array<Byte>^bytes )
{
   if ( (bytes == nullptr) || (bytes->Length == 0) )
      Console::WriteLine( "<none>" );
   else
   {
      for ( int i = 0; i < bytes->Length; i++ )
         Console::Write( "{0:X2} ", bytes[ i ] );
      Console::WriteLine();
   }
}

/* 
This code produces the following output.

Encoding the entire string:
System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

Encoding the characters from index 4 through 6:
System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // The characters to encode:
      //    Latin Small Letter Z (U+007A)
      //    Latin Small Letter A (U+0061)
      //    Combining Breve (U+0306)
      //    Latin Small Letter AE With Acute (U+01FD)
      //    Greek Small Letter Beta (U+03B2)
      //    a high-surrogate value (U+D8FF)
      //    a low-surrogate value (U+DCFF)
      String myStr = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";

      // Get different encodings.
      Encoding  u7    = Encoding.UTF7;
      Encoding  u8    = Encoding.UTF8;
      Encoding  u16LE = Encoding.Unicode;
      Encoding  u16BE = Encoding.BigEndianUnicode;
      Encoding  u32   = Encoding.UTF32;

      // Encode the entire string, and print out the counts and the resulting bytes.
      Console.WriteLine( "Encoding the entire string:" );
      PrintCountsAndBytes( myStr, u7 );
      PrintCountsAndBytes( myStr, u8 );
      PrintCountsAndBytes( myStr, u16LE );
      PrintCountsAndBytes( myStr, u16BE );
      PrintCountsAndBytes( myStr, u32 );

      Console.WriteLine();

      // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      Console.WriteLine( "Encoding the characters from index 4 through 6:" );
      PrintCountsAndBytes( myStr, 4, 3, u7 );
      PrintCountsAndBytes( myStr, 4, 3, u8 );
      PrintCountsAndBytes( myStr, 4, 3, u16LE );
      PrintCountsAndBytes( myStr, 4, 3, u16BE );
      PrintCountsAndBytes( myStr, 4, 3, u32 );
   }

   public static void PrintCountsAndBytes( String s, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( s );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( s.Length );
      Console.Write( " {0,-3} :", iMBC );

      // Encode the entire string.
      byte[] bytes = enc.GetBytes( s );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintCountsAndBytes( String s, int index, int count, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( s.ToCharArray(), index, count );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( count );
      Console.Write( " {0,-3} :", iMBC );

      // Encode a range of characters in the string.
      byte[] bytes = new byte[iBC];
      enc.GetBytes( s, index, count, bytes, bytes.GetLowerBound(0) );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintHexBytes( byte[] bytes )  {

      if (( bytes == null ) || ( bytes.Length == 0 ))
        {
            Console.WriteLine( "<none>" );
        }
        else  {
         for ( int i = 0; i < bytes.Length; i++ )
            Console.Write( "{0:X2} ", bytes[i] );
         Console.WriteLine();
      }
   }
}


/* 
This code produces the following output.

Encoding the entire string:
System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

Encoding the characters from index 4 through 6:
System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' The characters to encode:
      '    Latin Small Letter Z (U+007A)
      '    Latin Small Letter A (U+0061)
      '    Combining Breve (U+0306)
      '    Latin Small Letter AE With Acute (U+01FD)
      '    Greek Small Letter Beta (U+03B2)
      '    a high-surrogate value (U+D8FF)
      '    a low-surrogate value (U+DCFF)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2) & ChrW(&HD8FF) & ChrW(&HDCFF)

      ' Get different encodings.
      Dim u7 As Encoding = Encoding.UTF7
      Dim u8 As Encoding = Encoding.UTF8
      Dim u16LE As Encoding = Encoding.Unicode
      Dim u16BE As Encoding = Encoding.BigEndianUnicode
      Dim u32 As Encoding = Encoding.UTF32

      ' Encode the entire string, and print out the counts and the resulting bytes.
      Console.WriteLine("Encoding the entire string:")
      PrintCountsAndBytes(myStr, u7)
      PrintCountsAndBytes(myStr, u8)
      PrintCountsAndBytes(myStr, u16LE)
      PrintCountsAndBytes(myStr, u16BE)
      PrintCountsAndBytes(myStr, u32)

      Console.WriteLine()

      ' Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      Console.WriteLine("Encoding the characters from index 4 through 6:")
      PrintCountsAndBytes(myStr, 4, 3, u7)
      PrintCountsAndBytes(myStr, 4, 3, u8)
      PrintCountsAndBytes(myStr, 4, 3, u16LE)
      PrintCountsAndBytes(myStr, 4, 3, u16BE)
      PrintCountsAndBytes(myStr, 4, 3, u32)

   End Sub


   Overloads Public Shared Sub PrintCountsAndBytes(s As String, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(s)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(s.Length)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode the entire string.
      Dim bytes As Byte() = enc.GetBytes(s)

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Overloads Public Shared Sub PrintCountsAndBytes(s As String, index As Integer, count As Integer, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(s.ToCharArray(), index, count)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(count)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode a range of characters in the string.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      Dim bytes(iBC - 1) As Byte
      enc.GetBytes(s, index, count, bytes, bytes.GetLowerBound(0))

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Public Shared Sub PrintHexBytes(bytes() As Byte)

      If bytes Is Nothing OrElse bytes.Length = 0 Then
         Console.WriteLine("<none>")
      Else
         Dim i As Integer
         For i = 0 To bytes.Length - 1
            Console.Write("{0:X2} ", bytes(i))
         Next i
         Console.WriteLine()
      End If

   End Sub

End Class


'This code produces the following output.
'
'Encoding the entire string:
'System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
'System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00
'
'Encoding the characters from index 4 through 6:
'System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
'System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

설명

변환 되는 데이터를 순차 블록 에서만 사용할 수 있는 경우 (예: 스트림에서 읽은 데이터) 또는 데이터 양이 작은 블록으로 분할 해야 하는 경우에는 Decoder 메서드 또는 메서드에서 제공 하는 또는를 Encoder 파생 된 GetDecoder GetEncoder 클래스의 각 메서드에서 사용 해야 합니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. Encoding.GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우의 문자열 버전을 사용 해야 합니다 GetBytes .

  • 의 유니코드 문자 버퍼 버전에서는 GetBytes(Char*, Int32, Byte*, Int32) 특히 개체를 사용 Encoder 하거나 기존 버퍼에 삽입 하는 여러 호출을 통해 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

적용 대상

GetBytes(Char*, Int32, Byte*, Int32)

중요

이 API는 CLS 규격이 아닙니다.

파생 클래스에서 재정의되면 지정한 문자 포인터에서 시작하는 문자 집합을 지정한 바이트 포인터에서 시작하여 저장되는 바이트 시퀀스로 인코딩합니다.

public:
 virtual int GetBytes(char* chars, int charCount, System::Byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public virtual int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[System.CLSCompliant(false)]
public virtual int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
public virtual int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
abstract member GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
[<System.CLSCompliant(false)>]
abstract member GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
abstract member GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
[<System.CLSCompliant(false)>]
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int

매개 변수

chars
Char*

인코딩할 첫 번째 문자를 가리키는 포인터입니다.

charCount
Int32

인코딩할 문자 수입니다.

bytes
Byte*

결과 바이트 시퀀스를 쓰기 시작할 위치를 가리키는 포인터입니다.

byteCount
Int32

쓸 최대 바이트 수입니다.

반환

Int32

bytes 매개 변수가 가리키는 위치에 쓴 실제 바이트 수입니다.

특성

예외

chars이(가) null인 경우

또는

bytesnull입니다.

charCount 또는 byteCount가 0보다 작습니다.

byteCount가 결과 바이트 수보다 작은 경우

대체가 발생했습니다(자세한 내용은 .NET의 문자 인코딩 참조).

EncoderFallbackEncoderExceptionFallback로 설정됩니다.

설명

결과 바이트를 저장 하는 데 필요한 정확한 배열 크기를 계산 하려면 GetBytes 메서드를 호출 GetByteCount 합니다. 최대 배열 크기를 계산 하려면 메서드를 호출 GetMaxByteCount 합니다. 메서드는 일반적으로 더 GetByteCount 많은 메모리를 할당 하는 것을 허용 하지만 GetMaxByteCount 메서드는 일반적으로 더 빠르게 실행 됩니다.

변환할 데이터 (예: 데이터 스트림에서 읽은) 순차 블록에만 사용할 수 있거나 데이터 크기가 너무 커서 작은 블록으로 나눌 수 하는 데 필요한 사용 해야 하는 경우는 Decoder 또는 Encoder 는 에서제공하는개체GetDecoder 또는 GetEncoder 메서드를 각각 파생된 클래스입니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우의 문자열 버전을 사용 해야 합니다 GetBytes .

  • 의 유니코드 문자 버퍼 버전에서는 GetBytes(Char*, Int32, Byte*, Int32) 특히 개체를 사용 Encoder 하거나 기존 버퍼에 삽입 하는 여러 호출을 통해 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

추가 정보

적용 대상

GetBytes(Char[], Int32, Int32, Byte[], Int32)

파생 클래스에서 재정의되면 지정한 문자 배열의 문자 집합을 지정한 바이트 배열로 인코딩합니다.

public:
 abstract int GetBytes(cli::array <char> ^ chars, int charIndex, int charCount, cli::array <System::Byte> ^ bytes, int byteIndex);
public abstract int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex);
abstract member GetBytes : char[] * int * int * byte[] * int -> int
Public MustOverride Function GetBytes (chars As Char(), charIndex As Integer, charCount As Integer, bytes As Byte(), byteIndex As Integer) As Integer

매개 변수

chars
Char[]

인코딩할 문자 집합이 포함된 문자 배열입니다.

charIndex
Int32

인코딩할 첫 번째 문자의 인덱스입니다.

charCount
Int32

인코딩할 문자 수입니다.

bytes
Byte[]

결과 바이트 시퀀스를 포함할 바이트 배열입니다.

byteIndex
Int32

결과 바이트 시퀀스를 쓰기 시작할 인덱스입니다.

반환

Int32

bytes에 쓴 실제 바이트 수입니다.

예외

chars이(가) null인 경우

또는

bytes이(가) null인 경우

charIndex, charCount 또는 byteIndex가 0보다 작은 경우

또는

charIndexcharCountchars에서 올바른 범위를 나타내지 않습니다.

또는

byteIndexbytes의 유효한 인덱스가 아닌 경우

bytes의 용량(byteIndex ~ 배열 끝)이 부족해서 결과 바이트를 수용할 수 없는 경우

대체가 발생했습니다(자세한 내용은 .NET의 문자 인코딩 참조).

EncoderFallbackEncoderExceptionFallback로 설정됩니다.

예제

다음 예제에서는 문자 배열에서 3 개의 문자를 인코딩하고 문자를 인코딩하고 결과 바이트를 표시 하는 데 필요한 바이트 수를 결정 합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndBytes( array<Char>^chars, int index, int count, Encoding^ enc );
void PrintHexBytes( array<Byte>^bytes );
int main()
{
   
   // The characters to encode:
   //    Latin Small Letter Z (U+007A)
   //    Latin Small Letter A (U+0061)
   //    Combining Breve (U+0306)
   //    Latin Small Letter AE With Acute (U+01FD)
   //    Greek Small Letter Beta (U+03B2)
   //    a high-surrogate value (U+D8FF)
   //    a low-surrogate value (U+DCFF)
   array<Char>^myChars = gcnew array<Char>{
      L'z',L'a',L'\u0306',L'\u01FD',L'\u03B2',L'\xD8FF',L'\xDCFF'
   };
   
   // Get different encodings.
   Encoding^ u7 = Encoding::UTF7;
   Encoding^ u8 = Encoding::UTF8;
   Encoding^ u16LE = Encoding::Unicode;
   Encoding^ u16BE = Encoding::BigEndianUnicode;
   Encoding^ u32 = Encoding::UTF32;
   
   // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
   PrintCountsAndBytes( myChars, 4, 3, u7 );
   PrintCountsAndBytes( myChars, 4, 3, u8 );
   PrintCountsAndBytes( myChars, 4, 3, u16LE );
   PrintCountsAndBytes( myChars, 4, 3, u16BE );
   PrintCountsAndBytes( myChars, 4, 3, u32 );
}

void PrintCountsAndBytes( array<Char>^chars, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( chars, index, count );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( count );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode the array of chars.
   array<Byte>^bytes = enc->GetBytes( chars, index, count );
   
   // The following is an alternative way to encode the array of chars:
   // byte[] bytes = new byte[iBC];
   // enc.GetBytes( chars, index, count, bytes, bytes.GetLowerBound(0) );
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintHexBytes( array<Byte>^bytes )
{
   if ( (bytes == nullptr) || (bytes->Length == 0) )
      Console::WriteLine( "<none>" );
   else
   {
      for ( int i = 0; i < bytes->Length; i++ )
         Console::Write( "{0:X2} ", bytes[ i ] );
      Console::WriteLine();
   }
}

/* 
This code produces the following output.

System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // The characters to encode:
      //    Latin Small Letter Z (U+007A)
      //    Latin Small Letter A (U+0061)
      //    Combining Breve (U+0306)
      //    Latin Small Letter AE With Acute (U+01FD)
      //    Greek Small Letter Beta (U+03B2)
      //    a high-surrogate value (U+D8FF)
      //    a low-surrogate value (U+DCFF)
      char[] myChars = new char[] { 'z', 'a', '\u0306', '\u01FD', '\u03B2', '\uD8FF', '\uDCFF' };

      // Get different encodings.
      Encoding  u7    = Encoding.UTF7;
      Encoding  u8    = Encoding.UTF8;
      Encoding  u16LE = Encoding.Unicode;
      Encoding  u16BE = Encoding.BigEndianUnicode;
      Encoding  u32   = Encoding.UTF32;

      // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      PrintCountsAndBytes( myChars, 4, 3, u7 );
      PrintCountsAndBytes( myChars, 4, 3, u8 );
      PrintCountsAndBytes( myChars, 4, 3, u16LE );
      PrintCountsAndBytes( myChars, 4, 3, u16BE );
      PrintCountsAndBytes( myChars, 4, 3, u32 );
   }

   public static void PrintCountsAndBytes( char[] chars, int index, int count, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( chars, index, count );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( count );
      Console.Write( " {0,-3} :", iMBC );

      // Encode the array of chars.
      byte[] bytes = enc.GetBytes( chars, index, count );

      // The following is an alternative way to encode the array of chars:
      // byte[] bytes = new byte[iBC];
      // enc.GetBytes( chars, index, count, bytes, bytes.GetLowerBound(0) );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintHexBytes( byte[] bytes )  {

      if (( bytes == null ) || ( bytes.Length == 0 ))
        {
            Console.WriteLine( "<none>" );
        }
        else  {
         for ( int i = 0; i < bytes.Length; i++ )
            Console.Write( "{0:X2} ", bytes[i] );
         Console.WriteLine();
      }
   }
}


/* 
This code produces the following output.

System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' The characters to encode:
      '    Latin Small Letter Z (U+007A)
      '    Latin Small Letter A (U+0061)
      '    Combining Breve (U+0306)
      '    Latin Small Letter AE With Acute (U+01FD)
      '    Greek Small Letter Beta (U+03B2)
      '    a high-surrogate value (U+D8FF)
      '    a low-surrogate value (U+DCFF)
      Dim myChars() As Char = {"z"c, "a"c, ChrW(&H0306), ChrW(&H01FD), ChrW(&H03B2), ChrW(&HD8FF), ChrW(&HDCFF) }

      ' Get different encodings.
      Dim u7 As Encoding = Encoding.UTF7
      Dim u8 As Encoding = Encoding.UTF8
      Dim u16LE As Encoding = Encoding.Unicode
      Dim u16BE As Encoding = Encoding.BigEndianUnicode
      Dim u32 As Encoding = Encoding.UTF32

      ' Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      PrintCountsAndBytes(myChars, 4, 3, u7)
      PrintCountsAndBytes(myChars, 4, 3, u8)
      PrintCountsAndBytes(myChars, 4, 3, u16LE)
      PrintCountsAndBytes(myChars, 4, 3, u16BE)
      PrintCountsAndBytes(myChars, 4, 3, u32)

   End Sub


   Public Shared Sub PrintCountsAndBytes(chars() As Char, index As Integer, count As Integer, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(chars, index, count)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(count)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode the array of chars.
      Dim bytes As Byte() = enc.GetBytes(chars, index, count)

      ' The following is an alternative way to encode the array of chars:
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      ' Dim bytes(iBC - 1) As Byte
      ' enc.GetBytes( chars, index, count, bytes, bytes.GetLowerBound(0) )

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Public Shared Sub PrintHexBytes(bytes() As Byte)

      If bytes Is Nothing OrElse bytes.Length = 0 Then
         Console.WriteLine("<none>")
      Else
         Dim i As Integer
         For i = 0 To bytes.Length - 1
            Console.Write("{0:X2} ", bytes(i))
         Next i
         Console.WriteLine()
      End If

   End Sub

End Class


'This code produces the following output.
'
'System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
'System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

설명

에서 결과 바이트를 저장 하는 데 필요한 정확한 배열 크기를 계산 하려면 GetBytes 메서드를 호출 해야 합니다 GetByteCount . 최대 배열 크기를 계산 하려면 메서드를 호출 GetMaxByteCount 합니다. 메서드는 일반적으로 더 GetByteCount 많은 메모리를 할당 하는 것을 허용 하지만 GetMaxByteCount 메서드는 일반적으로 더 빠르게 실행 됩니다.

변환 되는 데이터를 순차 블록 에서만 사용할 수 있는 경우 (예: 스트림에서 읽은 데이터) 또는 데이터 양이 작은 블록으로 분할 해야 하는 경우에는 Decoder 메서드 또는 메서드에서 제공 하는 또는를 Encoder 파생 된 GetDecoder GetEncoder 클래스의 각 메서드에서 사용 해야 합니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. Encoding.GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우의 문자열 버전을 사용 해야 합니다 GetBytes .

  • 의 유니코드 문자 버퍼 버전에서는 GetBytes(Char*, Int32, Byte*, Int32) 특히 개체를 사용 Encoder 하거나 기존 버퍼에 삽입 하는 여러 호출을 통해 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

추가 정보

적용 대상

GetBytes(String, Int32, Int32, Byte[], Int32)

파생 클래스에서 재정의되면 지정한 문자열의 문자 집합을 지정한 바이트 배열로 인코딩합니다.

public:
 virtual int GetBytes(System::String ^ s, int charIndex, int charCount, cli::array <System::Byte> ^ bytes, int byteIndex);
public virtual int GetBytes (string s, int charIndex, int charCount, byte[] bytes, int byteIndex);
abstract member GetBytes : string * int * int * byte[] * int -> int
override this.GetBytes : string * int * int * byte[] * int -> int
Public Overridable Function GetBytes (s As String, charIndex As Integer, charCount As Integer, bytes As Byte(), byteIndex As Integer) As Integer

매개 변수

s
String

인코딩할 문자 집합이 포함된 문자열입니다.

charIndex
Int32

인코딩할 첫 번째 문자의 인덱스입니다.

charCount
Int32

인코딩할 문자 수입니다.

bytes
Byte[]

결과 바이트 시퀀스를 포함할 바이트 배열입니다.

byteIndex
Int32

결과 바이트 시퀀스를 쓰기 시작할 인덱스입니다.

반환

Int32

bytes에 쓴 실제 바이트 수입니다.

예외

s이(가) null인 경우

또는

bytes이(가) null인 경우

charIndex, charCount 또는 byteIndex가 0보다 작은 경우

또는

charIndexcharCountchars에서 올바른 범위를 나타내지 않습니다.

또는

byteIndexbytes의 유효한 인덱스가 아닌 경우

bytes의 용량(byteIndex ~ 배열 끝)이 부족해서 결과 바이트를 수용할 수 없는 경우

대체가 발생했습니다(자세한 내용은 .NET의 문자 인코딩 참조).

EncoderFallbackEncoderExceptionFallback로 설정됩니다.

예제

다음 예에서는 문자열 또는 문자열의 범위를 인코딩하고 문자를 인코딩하고 결과 바이트를 표시 하는 데 필요한 바이트 수를 결정 합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndBytes( String^ s, Encoding^ enc );
void PrintCountsAndBytes( String^ s, int index, int count, Encoding^ enc );
void PrintHexBytes( array<Byte>^bytes );
int main()
{
   
   // The characters to encode:
   //    Latin Small Letter Z (U+007A)
   //    Latin Small Letter A (U+0061)
   //    Combining Breve (U+0306)
   //    Latin Small Letter AE With Acute (U+01FD)
   //    Greek Small Letter Beta (U+03B2)
   //    a high-surrogate value (U+D8FF)
   //    a low-surrogate value (U+DCFF)
   String^ myStr = L"za\u0306\u01FD\u03B2\xD8FF\xDCFF";
   
   // Get different encodings.
   Encoding^ u7 = Encoding::UTF7;
   Encoding^ u8 = Encoding::UTF8;
   Encoding^ u16LE = Encoding::Unicode;
   Encoding^ u16BE = Encoding::BigEndianUnicode;
   Encoding^ u32 = Encoding::UTF32;
   
   // Encode the entire string, and print out the counts and the resulting bytes.
   Console::WriteLine( "Encoding the entire string:" );
   PrintCountsAndBytes( myStr, u7 );
   PrintCountsAndBytes( myStr, u8 );
   PrintCountsAndBytes( myStr, u16LE );
   PrintCountsAndBytes( myStr, u16BE );
   PrintCountsAndBytes( myStr, u32 );
   Console::WriteLine();
   
   // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
   Console::WriteLine( "Encoding the characters from index 4 through 6:" );
   PrintCountsAndBytes( myStr, 4, 3, u7 );
   PrintCountsAndBytes( myStr, 4, 3, u8 );
   PrintCountsAndBytes( myStr, 4, 3, u16LE );
   PrintCountsAndBytes( myStr, 4, 3, u16BE );
   PrintCountsAndBytes( myStr, 4, 3, u32 );
}

void PrintCountsAndBytes( String^ s, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( s );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( s->Length );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode the entire string.
   array<Byte>^bytes = enc->GetBytes( s );
   
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintCountsAndBytes( String^ s, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-30} :", enc );
   
   // Display the exact byte count.
   int iBC = enc->GetByteCount( s->ToCharArray(), index, count );
   Console::Write( " {0,-3}", iBC );
   
   // Display the maximum byte count.
   int iMBC = enc->GetMaxByteCount( count );
   Console::Write( " {0,-3} :", iMBC );
   
   // Encode a range of characters in the string.
   array<Byte>^bytes = gcnew array<Byte>(iBC);
   enc->GetBytes( s, index, count, bytes, bytes->GetLowerBound( 0 ) );
   
   // Display all the encoded bytes.
   PrintHexBytes( bytes );
}

void PrintHexBytes( array<Byte>^bytes )
{
   if ( (bytes == nullptr) || (bytes->Length == 0) )
      Console::WriteLine( "<none>" );
   else
   {
      for ( int i = 0; i < bytes->Length; i++ )
         Console::Write( "{0:X2} ", bytes[ i ] );
      Console::WriteLine();
   }
}

/* 
This code produces the following output.

Encoding the entire string:
System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

Encoding the characters from index 4 through 6:
System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // The characters to encode:
      //    Latin Small Letter Z (U+007A)
      //    Latin Small Letter A (U+0061)
      //    Combining Breve (U+0306)
      //    Latin Small Letter AE With Acute (U+01FD)
      //    Greek Small Letter Beta (U+03B2)
      //    a high-surrogate value (U+D8FF)
      //    a low-surrogate value (U+DCFF)
      String myStr = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";

      // Get different encodings.
      Encoding  u7    = Encoding.UTF7;
      Encoding  u8    = Encoding.UTF8;
      Encoding  u16LE = Encoding.Unicode;
      Encoding  u16BE = Encoding.BigEndianUnicode;
      Encoding  u32   = Encoding.UTF32;

      // Encode the entire string, and print out the counts and the resulting bytes.
      Console.WriteLine( "Encoding the entire string:" );
      PrintCountsAndBytes( myStr, u7 );
      PrintCountsAndBytes( myStr, u8 );
      PrintCountsAndBytes( myStr, u16LE );
      PrintCountsAndBytes( myStr, u16BE );
      PrintCountsAndBytes( myStr, u32 );

      Console.WriteLine();

      // Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      Console.WriteLine( "Encoding the characters from index 4 through 6:" );
      PrintCountsAndBytes( myStr, 4, 3, u7 );
      PrintCountsAndBytes( myStr, 4, 3, u8 );
      PrintCountsAndBytes( myStr, 4, 3, u16LE );
      PrintCountsAndBytes( myStr, 4, 3, u16BE );
      PrintCountsAndBytes( myStr, 4, 3, u32 );
   }

   public static void PrintCountsAndBytes( String s, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( s );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( s.Length );
      Console.Write( " {0,-3} :", iMBC );

      // Encode the entire string.
      byte[] bytes = enc.GetBytes( s );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintCountsAndBytes( String s, int index, int count, Encoding enc )  {

      // Display the name of the encoding used.
      Console.Write( "{0,-30} :", enc.ToString() );

      // Display the exact byte count.
      int iBC  = enc.GetByteCount( s.ToCharArray(), index, count );
      Console.Write( " {0,-3}", iBC );

      // Display the maximum byte count.
      int iMBC = enc.GetMaxByteCount( count );
      Console.Write( " {0,-3} :", iMBC );

      // Encode a range of characters in the string.
      byte[] bytes = new byte[iBC];
      enc.GetBytes( s, index, count, bytes, bytes.GetLowerBound(0) );

      // Display all the encoded bytes.
      PrintHexBytes( bytes );
   }

   public static void PrintHexBytes( byte[] bytes )  {

      if (( bytes == null ) || ( bytes.Length == 0 ))
        {
            Console.WriteLine( "<none>" );
        }
        else  {
         for ( int i = 0; i < bytes.Length; i++ )
            Console.Write( "{0:X2} ", bytes[i] );
         Console.WriteLine();
      }
   }
}


/* 
This code produces the following output.

Encoding the entire string:
System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00

Encoding the characters from index 4 through 6:
System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' The characters to encode:
      '    Latin Small Letter Z (U+007A)
      '    Latin Small Letter A (U+0061)
      '    Combining Breve (U+0306)
      '    Latin Small Letter AE With Acute (U+01FD)
      '    Greek Small Letter Beta (U+03B2)
      '    a high-surrogate value (U+D8FF)
      '    a low-surrogate value (U+DCFF)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2) & ChrW(&HD8FF) & ChrW(&HDCFF)

      ' Get different encodings.
      Dim u7 As Encoding = Encoding.UTF7
      Dim u8 As Encoding = Encoding.UTF8
      Dim u16LE As Encoding = Encoding.Unicode
      Dim u16BE As Encoding = Encoding.BigEndianUnicode
      Dim u32 As Encoding = Encoding.UTF32

      ' Encode the entire string, and print out the counts and the resulting bytes.
      Console.WriteLine("Encoding the entire string:")
      PrintCountsAndBytes(myStr, u7)
      PrintCountsAndBytes(myStr, u8)
      PrintCountsAndBytes(myStr, u16LE)
      PrintCountsAndBytes(myStr, u16BE)
      PrintCountsAndBytes(myStr, u32)

      Console.WriteLine()

      ' Encode three characters starting at index 4, and print out the counts and the resulting bytes.
      Console.WriteLine("Encoding the characters from index 4 through 6:")
      PrintCountsAndBytes(myStr, 4, 3, u7)
      PrintCountsAndBytes(myStr, 4, 3, u8)
      PrintCountsAndBytes(myStr, 4, 3, u16LE)
      PrintCountsAndBytes(myStr, 4, 3, u16BE)
      PrintCountsAndBytes(myStr, 4, 3, u32)

   End Sub


   Overloads Public Shared Sub PrintCountsAndBytes(s As String, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(s)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(s.Length)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode the entire string.
      Dim bytes As Byte() = enc.GetBytes(s)

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Overloads Public Shared Sub PrintCountsAndBytes(s As String, index As Integer, count As Integer, enc As Encoding)

      ' Display the name of the encoding used.
      Console.Write("{0,-30} :", enc.ToString())

      ' Display the exact byte count.
      Dim iBC As Integer = enc.GetByteCount(s.ToCharArray(), index, count)
      Console.Write(" {0,-3}", iBC)

      ' Display the maximum byte count.
      Dim iMBC As Integer = enc.GetMaxByteCount(count)
      Console.Write(" {0,-3} :", iMBC)

      ' Encode a range of characters in the string.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates the array with the exact number of elements required.
      Dim bytes(iBC - 1) As Byte
      enc.GetBytes(s, index, count, bytes, bytes.GetLowerBound(0))

      ' Display all the encoded bytes.
      PrintHexBytes(bytes)

   End Sub


   Public Shared Sub PrintHexBytes(bytes() As Byte)

      If bytes Is Nothing OrElse bytes.Length = 0 Then
         Console.WriteLine("<none>")
      Else
         Dim i As Integer
         For i = 0 To bytes.Length - 1
            Console.Write("{0:X2} ", bytes(i))
         Next i
         Console.WriteLine()
      End If

   End Sub

End Class


'This code produces the following output.
'
'Encoding the entire string:
'System.Text.UTF7Encoding       : 18  23  :7A 61 2B 41 77 59 42 2F 51 4F 79 32 50 2F 63 2F 77 2D
'System.Text.UTF8Encoding       : 12  24  :7A 61 CC 86 C7 BD CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 14  16  :7A 00 61 00 06 03 FD 01 B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 14  16  :00 7A 00 61 03 06 01 FD 03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 24  32  :7A 00 00 00 61 00 00 00 06 03 00 00 FD 01 00 00 B2 03 00 00 FF FC 04 00
'
'Encoding the characters from index 4 through 6:
'System.Text.UTF7Encoding       : 10  11  :2B 41 37 4C 59 2F 39 7A 2F 2D
'System.Text.UTF8Encoding       : 6   12  :CE B2 F1 8F B3 BF
'System.Text.UnicodeEncoding    : 6   8   :B2 03 FF D8 FF DC
'System.Text.UnicodeEncoding    : 6   8   :03 B2 D8 FF DC FF
'System.Text.UTF32Encoding      : 8   16  :B2 03 00 00 FF FC 04 00

설명

에서 결과 바이트를 저장 하는 데 필요한 정확한 배열 크기를 계산 하려면 GetBytes 메서드를 호출 해야 합니다 GetByteCount . 최대 배열 크기를 계산 하려면 메서드를 호출 GetMaxByteCount 합니다. 메서드는 일반적으로 더 GetByteCount 많은 메모리를 할당 하는 것을 허용 하지만 GetMaxByteCount 메서드는 일반적으로 더 빠르게 실행 됩니다.

변환 되는 데이터를 순차 블록 에서만 사용할 수 있는 경우 (예: 스트림에서 읽은 데이터) 또는 데이터 양이 작은 블록으로 분할 해야 하는 경우에는 Decoder 메서드 또는 메서드에서 제공 하는 또는를 Encoder 파생 된 GetDecoder GetEncoder 클래스의 각 메서드에서 사용 해야 합니다.

GetByteCount메서드는 유니코드 문자 집합을 인코딩할 바이트 수를 결정 하 고 GetBytes 메서드는 실제 인코딩을 수행 합니다. Encoding.GetBytes메서드는 Encoder.GetBytes 단일 입력 스트림에서 여러 변환을 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드 사용에 대 한 몇 가지 프로그래밍 고려 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다. 예를 들어 서로게이트 쌍을 포함 하는 문자 시퀀스는 높은 서로게이트로 끝날 수 있습니다. 는 Encoder 다음 호출이 시작 될 때 하위 서로게이트와 결합 될 수 있도록 high 서로게이트를 기억할 것입니다. Encoding는 상태를 유지할 수 없으므로 문자는로 전송 됩니다 EncoderFallback .

  • 앱에서 문자열 입력을 처리 하는 경우의 문자열 버전을 사용 해야 합니다 GetBytes .

  • 의 유니코드 문자 버퍼 버전에서는 GetBytes(Char*, Int32, Byte*, Int32) 특히 개체를 사용 Encoder 하거나 기존 버퍼에 삽입 하는 여러 호출을 통해 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetBytes 바이트 배열을 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

  • 대신 메서드를 사용 하는 것이 좋습니다 Encoder.Convert GetByteCount . 변환 메서드는 가능한 한 많은 데이터를 변환 하 고 출력 버퍼가 너무 작은 경우 예외를 throw 합니다. 스트림의 연속 인코딩에 대해이 방법을 선택 하는 것이 가장 좋습니다.

추가 정보

적용 대상