Encoding.GetByteCount 메서드

정의

파생 클래스에서 재정의되면 문자 집합을 인코딩하여 생성되는 바이트 수를 계산합니다.

오버로드

GetByteCount(Char[], Int32, Int32)

파생 클래스에서 재정의되면 지정한 문자 배열의 문자 집합을 인코딩하여 생성되는 바이트 수를 계산합니다.

GetByteCount(String, Int32, Int32)

파생 클래스에서 재정의할 경우, 지정된 문자열의 문자 집합을 인코딩하여 생성되는 바이트 수를 계산합니다.

GetByteCount(Char*, Int32)

파생 클래스에서 재정의되면 지정한 문자 포인터에서 시작하는 문자 집합을 인코딩하여 생성되는 바이트 수를 계산합니다.

GetByteCount(ReadOnlySpan<Char>)

파생 클래스에서 재정의할 경우, 지정된 문자 범위의 문자를 인코딩하여 생성되는 바이트 수를 계산합니다.

GetByteCount(Char[])

파생 클래스에서 재정의되면 지정한 문자 배열의 모든 문자를 인코딩하여 생성되는 바이트 수를 계산합니다.

GetByteCount(String)

파생 클래스에서 재정의되면 지정된 문자열의 문자를 인코딩하여 생성되는 바이트 수를 계산합니다.

GetByteCount(Char[], Int32, Int32)

파생 클래스에서 재정의되면 지정한 문자 배열의 문자 집합을 인코딩하여 생성되는 바이트 수를 계산합니다.

public:
 abstract int GetByteCount(cli::array <char> ^ chars, int index, int count);
public abstract int GetByteCount (char[] chars, int index, int count);
abstract member GetByteCount : char[] * int * int -> int
Public MustOverride Function GetByteCount (chars As Char(), index As Integer, count As Integer) As Integer

매개 변수

chars
Char[]

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

index
Int32

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

count
Int32

인코딩할 문자 수입니다.

반환

Int32

지정한 문자를 인코딩할 경우 생성되는 바이트 수입니다.

예외

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

설명

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

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

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

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다.

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

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

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

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

추가 정보

적용 대상

GetByteCount(String, Int32, Int32)

파생 클래스에서 재정의할 경우, 지정된 문자열의 문자 집합을 인코딩하여 생성되는 바이트 수를 계산합니다.

public:
 int GetByteCount(System::String ^ s, int index, int count);
public int GetByteCount (string s, int index, int count);
member this.GetByteCount : string * int * int -> int
Public Function GetByteCount (s As String, index As Integer, count As Integer) As Integer

매개 변수

s
String

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

index
Int32

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

count
Int32

인코딩할 문자 수입니다.

반환

Int32

문자열을 인코딩하여 생성되는 바이트 수입니다.

예제

다음 예제에서는 문자 배열에서 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 메서드는 일반적으로 더 빠르게 실행 됩니다.

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

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

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다.

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

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

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

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

적용 대상

GetByteCount(Char*, Int32)

중요

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

파생 클래스에서 재정의되면 지정한 문자 포인터에서 시작하는 문자 집합을 인코딩하여 생성되는 바이트 수를 계산합니다.

public:
 virtual int GetByteCount(char* chars, int count);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public virtual int GetByteCount (char* chars, int count);
[System.CLSCompliant(false)]
public virtual int GetByteCount (char* chars, int count);
public virtual int GetByteCount (char* chars, int count);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetByteCount (char* chars, int count);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetByteCount (char* chars, int count);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
abstract member GetByteCount : nativeptr<char> * int -> int
override this.GetByteCount : nativeptr<char> * int -> int
[<System.CLSCompliant(false)>]
abstract member GetByteCount : nativeptr<char> * int -> int
override this.GetByteCount : nativeptr<char> * int -> int
abstract member GetByteCount : nativeptr<char> * int -> int
override this.GetByteCount : nativeptr<char> * int -> int
[<System.CLSCompliant(false)>]
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member GetByteCount : nativeptr<char> * int -> int
override this.GetByteCount : nativeptr<char> * int -> int
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member GetByteCount : nativeptr<char> * int -> int
override this.GetByteCount : nativeptr<char> * int -> int

매개 변수

chars
Char*

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

count
Int32

인코딩할 문자 수입니다.

반환

Int32

지정한 문자를 인코딩할 경우 생성되는 바이트 수입니다.

특성

예외

chars이(가) null인 경우

count가 0보다 작은 경우

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

EncoderFallbackEncoderExceptionFallback로 설정됩니다.

설명

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

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

및의 몇 가지 버전이 GetByteCount GetBytes 지원 됩니다. 다음은 이러한 메서드를 사용할 때 고려해 야 할 몇 가지 사항입니다.

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다.

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

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

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

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

추가 정보

적용 대상

GetByteCount(ReadOnlySpan<Char>)

파생 클래스에서 재정의할 경우, 지정된 문자 범위의 문자를 인코딩하여 생성되는 바이트 수를 계산합니다.

public:
 virtual int GetByteCount(ReadOnlySpan<char> chars);
public virtual int GetByteCount (ReadOnlySpan<char> chars);
abstract member GetByteCount : ReadOnlySpan<char> -> int
override this.GetByteCount : ReadOnlySpan<char> -> int
Public Overridable Function GetByteCount (chars As ReadOnlySpan(Of Char)) As Integer

매개 변수

chars
ReadOnlySpan<Char>

인코딩할 문자 범위입니다.

반환

Int32

지정된 문자 범위를 인코딩하여 생성된 바이트 수입니다.

설명

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

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

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

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다.

  • 앱에서 문자 입력 범위를 처리 하는 경우의 범위 버전을 GetBytes 권장 합니다.

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

적용 대상

GetByteCount(Char[])

파생 클래스에서 재정의되면 지정한 문자 배열의 모든 문자를 인코딩하여 생성되는 바이트 수를 계산합니다.

public:
 virtual int GetByteCount(cli::array <char> ^ chars);
public virtual int GetByteCount (char[] chars);
abstract member GetByteCount : char[] -> int
override this.GetByteCount : char[] -> int
Public Overridable Function GetByteCount (chars As Char()) As Integer

매개 변수

chars
Char[]

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

반환

Int32

지정한 문자 배열의 모든 문자를 인코딩하여 생성되는 바이트 수입니다.

예외

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

설명

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

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

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

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다.

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

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

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

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

추가 정보

적용 대상

GetByteCount(String)

파생 클래스에서 재정의되면 지정된 문자열의 문자를 인코딩하여 생성되는 바이트 수를 계산합니다.

public:
 virtual int GetByteCount(System::String ^ s);
public virtual int GetByteCount (string s);
abstract member GetByteCount : string -> int
override this.GetByteCount : string -> int
Public Overridable Function GetByteCount (s As String) As Integer

매개 변수

s
String

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

반환

Int32

지정한 문자를 인코딩할 경우 생성되는 바이트 수입니다.

예외

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

설명

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

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

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

  • 앱은 많은 입력 문자를 코드 페이지로 인코딩하고 여러 호출을 사용 하 여 문자를 처리 해야 할 수 있습니다. 이 경우에는 사용 중인 개체에 의해 유지 되는 상태를 고려 하 여 호출 간의 상태를 유지 해야 Encoder 합니다.

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

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

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

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

추가 정보

적용 대상