Encoding.GetMaxByteCount(Int32) 메서드

정의

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

public:
 abstract int GetMaxByteCount(int charCount);
public abstract int GetMaxByteCount (int charCount);
abstract member GetMaxByteCount : int -> int
Public MustOverride Function GetMaxByteCount (charCount As Integer) As Integer

매개 변수

charCount
Int32

인코딩할 문자 수입니다.

반환

Int32

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

예외

charCount가 0보다 작은 경우

대체가 발생했습니다(자세한 내용은 .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

설명

charCount Char .Net 내부적으로는 유니코드 문자를 나타내기 위해 u t f-16을 사용 하기 때문에 매개 변수는 인코딩할 유니코드 문자를 나타내는 개체 수를 실제로 지정 합니다. 따라서 대부분의 유니코드 문자를 하나의 개체로 나타낼 수 Char 있지만 서로게이트 쌍으로 표현 되는 유니코드 문자에는 두 개의 Char 개체가 필요 합니다.

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

GetMaxByteCount현재 선택 된에 대 한 최악의 경우를 포함 하 여 최악의 숫자를 검색 EncoderFallback 합니다. 잠재적으로 크기가 높은 문자열을 사용 하 여 대체 (fallback)를 선택 하는 경우는 GetMaxByteCount 특히 인코딩에 대 한 최악의 경우에는 모든 문자에 대 한 모드를 전환 해야 하는 경우에 많은 값을 검색 예를 들어이 문제는 ISO-2022-JP에 대해 발생할 수 있습니다. 자세한 내용은 블로그 게시물의 "GetMaxByteCount () 및 GetMaxCharCount ()?블로그 게시물을 참조 하십시오.

대부분의 경우이 메서드는 작은 문자열의 적절 한 값을 검색 합니다. 큰 문자열의 경우 매우 큰 버퍼를 사용 하 고 드문 경우에는 더 적절 한 버퍼가 너무 작은 경우에 오류를 catch 하도록 선택 해야 할 수 있습니다. 또는을 사용 하 여 다른 방법을 고려해 볼 수도 GetByteCount 있습니다 Encoder.Convert .

를 사용 하는 경우 GetMaxByteCount 입력 버퍼의 최대 크기를 기준으로 출력 버퍼를 할당 해야 합니다. 출력 버퍼의 크기가 제한 된 경우에는 메서드를 사용할 수 있습니다 Convert .

GetMaxByteCount 이전 디코더 작업에서 남겨진 잠재적 서로게이트를 고려 합니다. 디코더가 값 1을 메서드에 전달 하는 것은 ASCII와 같은 싱글바이트 인코딩에 대해 2를 검색 합니다. 이 정보가 필요한 경우에는 속성을 사용 해야 합니다 IsSingleByte .

참고

GetMaxByteCount(N)이 반드시와 동일한 값은 아닙니다 N* GetMaxByteCount(1) .

구현자 참고

모든 Encoding 구현은이 메서드의 계산 결과에 따라 버퍼 크기를 조정 하는 경우 버퍼 오버플로 예외가 발생 하지 않도록 보장 해야 합니다.

적용 대상

추가 정보