Encoding.GetCharCount 메서드

정의

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

오버로드

GetCharCount(Byte[])

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

GetCharCount(ReadOnlySpan<Byte>)

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

GetCharCount(Byte*, Int32)

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

GetCharCount(Byte[], Int32, Int32)

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

GetCharCount(Byte[])

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

public:
 virtual int GetCharCount(cli::array <System::Byte> ^ bytes);
public virtual int GetCharCount (byte[] bytes);
abstract member GetCharCount : byte[] -> int
override this.GetCharCount : byte[] -> int
Public Overridable Function GetCharCount (bytes As Byte()) As Integer

매개 변수

bytes
Byte[]

디코딩할 바이트 시퀀스를 포함하는 바이트 배열입니다.

반환

Int32

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

예외

bytes이(가) null인 경우

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

DecoderFallbackDecoderExceptionFallback로 설정됩니다.

예제

다음 예제에서는 문자열을 바이트 배열로 인코딩한 다음 바이트를 문자 배열로 디코딩합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndChars( array<Byte>^bytes, Encoding^ enc );
int main()
{
   
   // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
   Encoding^ u32LE = Encoding::GetEncoding( "utf-32" );
   Encoding^ u32BE = Encoding::GetEncoding( "utf-32BE" );
   
   // Use a string containing the following characters:
   //    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)
   String^ myStr = "za\u0306\u01FD\u03B2";
   
   // Encode the string using the big-endian byte order.
   array<Byte>^barrBE = gcnew array<Byte>(u32BE->GetByteCount( myStr ));
   u32BE->GetBytes( myStr, 0, myStr->Length, barrBE, 0 );
   
   // Encode the string using the little-endian byte order.
   array<Byte>^barrLE = gcnew array<Byte>(u32LE->GetByteCount( myStr ));
   u32LE->GetBytes( myStr, 0, myStr->Length, barrLE, 0 );
   
   // Get the char counts, and decode the byte arrays.
   Console::Write( "BE array with BE encoding : " );
   PrintCountsAndChars( barrBE, u32BE );
   Console::Write( "LE array with LE encoding : " );
   PrintCountsAndChars( barrLE, u32LE );
}

void PrintCountsAndChars( array<Byte>^bytes, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-25} :", enc );
   
   // Display the exact character count.
   int iCC = enc->GetCharCount( bytes );
   Console::Write( " {0,-3}", iCC );
   
   // Display the maximum character count.
   int iMCC = enc->GetMaxCharCount( bytes->Length );
   Console::Write( " {0,-3} :", iMCC );
   
   // Decode the bytes and display the characters.
   array<Char>^chars = enc->GetChars( bytes );
   Console::WriteLine( chars );
}

/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ
LE array with LE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Encoding u32LE = Encoding.GetEncoding( "utf-32" );
      Encoding u32BE = Encoding.GetEncoding( "utf-32BE" );

      // Use a string containing the following characters:
      //    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)
      String myStr = "za\u0306\u01FD\u03B2";

      // Encode the string using the big-endian byte order.
      byte[] barrBE = new byte[u32BE.GetByteCount( myStr )];
      u32BE.GetBytes( myStr, 0, myStr.Length, barrBE, 0 );

      // Encode the string using the little-endian byte order.
      byte[] barrLE = new byte[u32LE.GetByteCount( myStr )];
      u32LE.GetBytes( myStr, 0, myStr.Length, barrLE, 0 );

      // Get the char counts, and decode the byte arrays.
      Console.Write( "BE array with BE encoding : " );
      PrintCountsAndChars( barrBE, u32BE );
      Console.Write( "LE array with LE encoding : " );
      PrintCountsAndChars( barrLE, u32LE );
   }

   public static void PrintCountsAndChars( byte[] bytes, Encoding enc )  {

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

      // Display the exact character count.
      int iCC  = enc.GetCharCount( bytes );
      Console.Write( " {0,-3}", iCC );

      // Display the maximum character count.
      int iMCC = enc.GetMaxCharCount( bytes.Length );
      Console.Write( " {0,-3} :", iMCC );

      // Decode the bytes and display the characters.
      char[] chars = enc.GetChars( bytes );
      Console.WriteLine( chars );
   }
}


/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ
LE array with LE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Dim u32LE As Encoding = Encoding.GetEncoding("utf-32")
      Dim u32BE As Encoding = Encoding.GetEncoding("utf-32BE")

      ' Use a string containing the following characters:
      '    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)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2) 

      ' Encode the string using the big-endian byte order.
      ' 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 barrBE(u32BE.GetByteCount(myStr) - 1) As Byte
      u32BE.GetBytes(myStr, 0, myStr.Length, barrBE, 0)

      ' Encode the string using the little-endian byte order.
      ' 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 barrLE(u32LE.GetByteCount(myStr) - 1) As Byte
      u32LE.GetBytes(myStr, 0, myStr.Length, barrLE, 0)

      ' Get the char counts, and decode the byte arrays.
      Console.Write("BE array with BE encoding : ")
      PrintCountsAndChars(barrBE, u32BE)
      Console.Write("LE array with LE encoding : ")
      PrintCountsAndChars(barrLE, u32LE)

   End Sub


   Public Shared Sub PrintCountsAndChars(bytes() As Byte, enc As Encoding)

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

      ' Display the exact character count.
      Dim iCC As Integer = enc.GetCharCount(bytes)
      Console.Write(" {0,-3}", iCC)

      ' Display the maximum character count.
      Dim iMCC As Integer = enc.GetMaxCharCount(bytes.Length)
      Console.Write(" {0,-3} :", iMCC)

      ' Decode the bytes and display the characters.
      Dim chars As Char() = enc.GetChars(bytes)
      Console.WriteLine(chars)

   End Sub

End Class


'This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.
'
'BE array with BE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ
'LE array with LE encoding : System.Text.UTF32Encoding : 5   12  :zăǽβ

설명

에서 결과 문자를 저장 하는 데 필요한 정확한 배열 크기를 계산 하려면 GetChars(Byte[]) 메서드를 사용 해야 합니다 GetCharCount(Byte[]) . 최대 배열 크기를 계산 하려면 메서드를 사용 해야 합니다 GetMaxCharCount(Int32) . 메서드는 일반적으로 더 GetCharCount(Byte[]) 많은 메모리를 할당 하는 것을 허용 하지만 GetMaxCharCount 메서드는 일반적으로 더 빠르게 실행 됩니다.

GetCharCount(Byte[])메서드는 바이트 시퀀스를 디코딩하는 문자 수를 결정 하 고 GetChars(Byte[]) 메서드는 실제 디코딩을 수행 합니다. Encoding.GetChars메서드는 Decoder.GetChars 단일 입력 스트림에서 여러 패스를 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

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

  • 앱은 코드 페이지에서 여러 입력 바이트를 디코딩하고 여러 호출을 사용 하 여 바이트를 처리 해야 할 수 있습니다. 이 경우 호출 간의 상태를 유지 해야 합니다.

  • 앱에서 문자열 출력을 처리 하는 경우 메서드를 사용 해야 합니다 GetString . 이 메서드는 문자열 길이를 확인 하 고 버퍼를 할당 해야 하므로 약간 더 느리지만 결과 String 형식을 선호 합니다.

  • 바이트 버전의에서는 GetChars(Byte*, Int32, Char*, Int32) 특히 대량 버퍼를 여러 번 호출 하 여 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetChars(Byte[], Int32, Int32, Char[], Int32) 출력 문자 버퍼를 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

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

추가 정보

적용 대상

GetCharCount(ReadOnlySpan<Byte>)

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

public:
 virtual int GetCharCount(ReadOnlySpan<System::Byte> bytes);
public virtual int GetCharCount (ReadOnlySpan<byte> bytes);
abstract member GetCharCount : ReadOnlySpan<byte> -> int
override this.GetCharCount : ReadOnlySpan<byte> -> int
Public Overridable Function GetCharCount (bytes As ReadOnlySpan(Of Byte)) As Integer

매개 변수

bytes
ReadOnlySpan<Byte>

디코딩할 읽기 전용 바이트 범위입니다.

반환

Int32

바이트 범위를 디코딩하여 생성되는 문자의 수입니다.

설명

결과 문자를 저장 해야 하는 정확한 배열 크기를 계산 하려면 GetChars 메서드를 사용 해야 합니다 GetCharCount . 최대 배열 크기를 계산 하려면 메서드를 사용 GetMaxCharCount 합니다. 메서드는 일반적으로 더 GetCharCount 많은 메모리를 할당 하는 것을 허용 하지만 GetMaxCharCount 메서드는 일반적으로 더 빠르게 실행 됩니다.

GetCharCount메서드는 바이트 시퀀스를 디코딩하는 문자 수를 결정 하 고 GetChars 메서드는 실제 디코딩을 수행 합니다. GetChars메서드는 Decoder.GetChars 단일 입력 스트림에서 여러 패스를 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

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

  • 앱은 코드 페이지에서 여러 입력 바이트를 디코딩하고 여러 호출을 사용 하 여 바이트를 처리 해야 할 수 있습니다. 이 경우 호출 간의 상태를 유지 해야 합니다.

  • 앱에서 문자열 출력을 처리 하는 경우 메서드를 사용 하는 것이 좋습니다 GetString . 이 메서드는 문자열 길이를 확인 하 고 버퍼를 할당 해야 하므로 약간 더 느리지만 결과 String 형식을 선호 합니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetChars(Byte[], Int32, Int32, Char[], Int32) 출력 문자 버퍼를 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

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

적용 대상

GetCharCount(Byte*, Int32)

중요

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

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

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

매개 변수

bytes
Byte*

디코딩할 첫 번째 바이트를 가리키는 포인터입니다.

count
Int32

디코딩할 바이트 수입니다.

반환

Int32

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

특성

예외

bytes이(가) null인 경우

count가 0보다 작은 경우

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

DecoderFallbackDecoderExceptionFallback로 설정됩니다.

설명

결과 문자를 저장 해야 하는 정확한 배열 크기를 계산 하려면 GetChars 메서드를 사용 해야 합니다 GetCharCount . 최대 배열 크기를 계산 하려면 메서드를 사용 GetMaxCharCount 합니다. 메서드는 일반적으로 더 GetCharCount 많은 메모리를 할당 하는 것을 허용 하지만 GetMaxCharCount 메서드는 일반적으로 더 빠르게 실행 됩니다.

GetCharCount메서드는 바이트 시퀀스를 디코딩하는 문자 수를 결정 하 고 GetChars 메서드는 실제 디코딩을 수행 합니다. GetChars메서드는 Decoder.GetChars 단일 입력 스트림에서 여러 패스를 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

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

  • 앱은 코드 페이지에서 여러 입력 바이트를 디코딩하고 여러 호출을 사용 하 여 바이트를 처리 해야 할 수 있습니다. 이 경우 호출 간의 상태를 유지 해야 합니다.

  • 앱에서 문자열 출력을 처리 하는 경우 메서드를 사용 하는 것이 좋습니다 GetString . 이 메서드는 문자열 길이를 확인 하 고 버퍼를 할당 해야 하므로 약간 더 느리지만 결과 String 형식을 선호 합니다.

  • 바이트 버전의에서는 GetChars(Byte*, Int32, Char*, Int32) 특히 대량 버퍼를 여러 번 호출 하 여 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetChars(Byte[], Int32, Int32, Char[], Int32) 출력 문자 버퍼를 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

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

추가 정보

적용 대상

GetCharCount(Byte[], Int32, Int32)

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

public:
 abstract int GetCharCount(cli::array <System::Byte> ^ bytes, int index, int count);
public abstract int GetCharCount (byte[] bytes, int index, int count);
abstract member GetCharCount : byte[] * int * int -> int
Public MustOverride Function GetCharCount (bytes As Byte(), index As Integer, count As Integer) As Integer

매개 변수

bytes
Byte[]

디코딩할 바이트 시퀀스를 포함하는 바이트 배열입니다.

index
Int32

디코딩할 첫 번째 바이트의 인덱스입니다.

count
Int32

디코딩할 바이트 수입니다.

반환

Int32

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

예외

bytes이(가) null인 경우

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

또는

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

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

DecoderFallbackDecoderExceptionFallback로 설정됩니다.

예제

다음 예제에서는 문자열을 한 인코딩에서 다른 인코딩으로 변환 합니다.

using namespace System;
using namespace System::Text;

int main()
{
   String^ unicodeString = "This string contains the unicode character Pi (\u03a0)";
   
   // Create two different encodings.
   Encoding^ ascii = Encoding::ASCII;
   Encoding^ unicode = Encoding::Unicode;
   
   // Convert the string into a byte array.
   array<Byte>^unicodeBytes = unicode->GetBytes( unicodeString );
   
   // Perform the conversion from one encoding to the other.
   array<Byte>^asciiBytes = Encoding::Convert( unicode, ascii, unicodeBytes );
   
   // Convert the new Byte into[] a char and[] then into a string.
   array<Char>^asciiChars = gcnew array<Char>(ascii->GetCharCount( asciiBytes, 0, asciiBytes->Length ));
   ascii->GetChars( asciiBytes, 0, asciiBytes->Length, asciiChars, 0 );
   String^ asciiString = gcnew String( asciiChars );
   
   // Display the strings created before and after the conversion.
   Console::WriteLine( "Original String*: {0}", unicodeString );
   Console::WriteLine( "Ascii converted String*: {0}", asciiString );
}
// The example displays the following output:
//    Original string: This string contains the unicode character Pi (Π)
//    Ascii converted string: This string contains the unicode character Pi (?)
using System;
using System.Text;

class Example
{
   static void Main()
   {
      string unicodeString = "This string contains the unicode character Pi (\u03a0)";

      // Create two different encodings.
      Encoding ascii = Encoding.ASCII;
      Encoding unicode = Encoding.Unicode;

      // Convert the string into a byte array.
      byte[] unicodeBytes = unicode.GetBytes(unicodeString);

      // Perform the conversion from one encoding to the other.
      byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
         
      // Convert the new byte[] into a char[] and then into a string.
      char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
      ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
      string asciiString = new string(asciiChars);

      // Display the strings created before and after the conversion.
      Console.WriteLine("Original string: {0}", unicodeString);
      Console.WriteLine("Ascii converted string: {0}", asciiString);
   }
}
// The example displays the following output:
//    Original string: This string contains the unicode character Pi (Π)
//    Ascii converted string: This string contains the unicode character Pi (?)
Imports System.Text

Class Example
   Shared Sub Main()
      Dim unicodeString As String = "This string contains the unicode character Pi (" & ChrW(&H03A0) & ")"

      ' Create two different encodings.
      Dim ascii As Encoding = Encoding.ASCII
      Dim unicode As Encoding = Encoding.Unicode

      ' Convert the string into a byte array.
      Dim unicodeBytes As Byte() = unicode.GetBytes(unicodeString)

      ' Perform the conversion from one encoding to the other.
      Dim asciiBytes As Byte() = Encoding.Convert(unicode, ascii, unicodeBytes)

      ' Convert the new byte array into a char array and then into a string.
      Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)-1) As Char
      ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
      Dim asciiString As New String(asciiChars)

      ' Display the strings created before and after the conversion.
      Console.WriteLine("Original string: {0}", unicodeString)
      Console.WriteLine("Ascii converted string: {0}", asciiString)
   End Sub
End Class
' The example displays the following output:
'    Original string: This string contains the unicode character Pi (Π)
'    Ascii converted string: This string contains the unicode character Pi (?)

다음 예제에서는 문자열을 바이트 배열로 인코딩한 다음 바이트 범위를 문자 배열로 디코딩합니다.

using namespace System;
using namespace System::Text;
void PrintCountsAndChars( array<Byte>^bytes, int index, int count, Encoding^ enc );
int main()
{
   
   // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
   Encoding^ u32LE = Encoding::GetEncoding( "utf-32" );
   Encoding^ u32BE = Encoding::GetEncoding( "utf-32BE" );
   
   // Use a string containing the following characters:
   //    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)
   String^ myStr = "za\u0306\u01FD\u03B2";
   
   // Encode the string using the big-endian byte order.
   array<Byte>^barrBE = gcnew array<Byte>(u32BE->GetByteCount( myStr ));
   u32BE->GetBytes( myStr, 0, myStr->Length, barrBE, 0 );
   
   // Encode the string using the little-endian byte order.
   array<Byte>^barrLE = gcnew array<Byte>(u32LE->GetByteCount( myStr ));
   u32LE->GetBytes( myStr, 0, myStr->Length, barrLE, 0 );
   
   // Get the char counts, decode eight bytes starting at index 0,
   // and print out the counts and the resulting bytes.
   Console::Write( "BE array with BE encoding : " );
   PrintCountsAndChars( barrBE, 0, 8, u32BE );
   Console::Write( "LE array with LE encoding : " );
   PrintCountsAndChars( barrLE, 0, 8, u32LE );
}

void PrintCountsAndChars( array<Byte>^bytes, int index, int count, Encoding^ enc )
{
   
   // Display the name of the encoding used.
   Console::Write( "{0,-25} :", enc );
   
   // Display the exact character count.
   int iCC = enc->GetCharCount( bytes, index, count );
   Console::Write( " {0,-3}", iCC );
   
   // Display the maximum character count.
   int iMCC = enc->GetMaxCharCount( count );
   Console::Write( " {0,-3} :", iMCC );
   
   // Decode the bytes and display the characters.
   array<Char>^chars = enc->GetChars( bytes, index, count );
   
   // The following is an alternative way to decode the bytes:
   // Char[] chars = new Char[iCC];
   // enc->GetChars( bytes, index, count, chars, 0 );
   Console::WriteLine( chars );
}

/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

*/
using System;
using System.Text;

public class SamplesEncoding  {

   public static void Main()  {

      // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Encoding u32LE = Encoding.GetEncoding( "utf-32" );
      Encoding u32BE = Encoding.GetEncoding( "utf-32BE" );

      // Use a string containing the following characters:
      //    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)
      String myStr = "za\u0306\u01FD\u03B2";

      // Encode the string using the big-endian byte order.
      byte[] barrBE = new byte[u32BE.GetByteCount( myStr )];
      u32BE.GetBytes( myStr, 0, myStr.Length, barrBE, 0 );

      // Encode the string using the little-endian byte order.
      byte[] barrLE = new byte[u32LE.GetByteCount( myStr )];
      u32LE.GetBytes( myStr, 0, myStr.Length, barrLE, 0 );

      // Get the char counts, decode eight bytes starting at index 0,
      // and print out the counts and the resulting bytes.
      Console.Write( "BE array with BE encoding : " );
      PrintCountsAndChars( barrBE, 0, 8, u32BE );
      Console.Write( "LE array with LE encoding : " );
      PrintCountsAndChars( barrLE, 0, 8, u32LE );
   }

   public static void PrintCountsAndChars( byte[] bytes, int index, int count, Encoding enc )  {

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

      // Display the exact character count.
      int iCC  = enc.GetCharCount( bytes, index, count );
      Console.Write( " {0,-3}", iCC );

      // Display the maximum character count.
      int iMCC = enc.GetMaxCharCount( count );
      Console.Write( " {0,-3} :", iMCC );

      // Decode the bytes and display the characters.
      char[] chars = enc.GetChars( bytes, index, count );

      // The following is an alternative way to decode the bytes:
      // char[] chars = new char[iCC];
      // enc.GetChars( bytes, index, count, chars, 0 );

      Console.WriteLine( chars );
   }
}


/* 
This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.

BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

*/
Imports System.Text

Public Class SamplesEncoding   

   Public Shared Sub Main()

      ' Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Dim u32LE As Encoding = Encoding.GetEncoding("utf-32")
      Dim u32BE As Encoding = Encoding.GetEncoding("utf-32BE")

      ' Use a string containing the following characters:
      '    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)
      Dim myStr As String = "za" & ChrW(&H0306) & ChrW(&H01FD) & ChrW(&H03B2)

      ' Encode the string using the big-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates barrBE with the exact number of elements required.
      Dim barrBE(u32BE.GetByteCount(myStr) - 1) As Byte
      u32BE.GetBytes(myStr, 0, myStr.Length, barrBE, 0)

      ' Encode the string using the little-endian byte order.
      ' NOTE: In VB.NET, arrays contain one extra element by default.
      '       The following line creates barrLE with the exact number of elements required.
      Dim barrLE(u32LE.GetByteCount(myStr) - 1) As Byte
      u32LE.GetBytes(myStr, 0, myStr.Length, barrLE, 0)

      ' Get the char counts, decode eight bytes starting at index 0,
      ' and print out the counts and the resulting bytes.
      Console.Write("BE array with BE encoding : ")
      PrintCountsAndChars(barrBE, 0, 8, u32BE)
      Console.Write("LE array with LE encoding : ")
      PrintCountsAndChars(barrLE, 0, 8, u32LE)

   End Sub


   Public Shared Sub PrintCountsAndChars(bytes() As Byte, index As Integer, count As Integer, enc As Encoding)

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

      ' Display the exact character count.
      Dim iCC As Integer = enc.GetCharCount(bytes, index, count)
      Console.Write(" {0,-3}", iCC)

      ' Display the maximum character count.
      Dim iMCC As Integer = enc.GetMaxCharCount(count)
      Console.Write(" {0,-3} :", iMCC)

      ' Decode the bytes.
      Dim chars As Char() = enc.GetChars(bytes, index, count)

      ' The following is an alternative way to decode the bytes:
      ' 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 chars(iCC - 1) As Char
      ' enc.GetChars( bytes, index, count, chars, 0 )

      ' Display the characters.
      Console.WriteLine(chars)

   End Sub

End Class


'This code produces the following output.  The question marks take the place of characters that cannot be displayed at the console.
'
'BE array with BE encoding : System.Text.UTF32Encoding : 2   6   :za
'LE array with LE encoding : System.Text.UTF32Encoding : 2   6   :za

설명

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

GetCharCount메서드는 바이트 시퀀스를 디코딩하는 문자 수를 결정 하 고 GetChars 메서드는 실제 디코딩을 수행 합니다. GetChars메서드는 Decoder.GetChars 단일 입력 스트림에서 여러 패스를 처리 하는 메서드와 달리 불연속 변환을 필요로 합니다.

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

  • 앱은 코드 페이지에서 여러 입력 바이트를 디코딩하고 여러 호출을 사용 하 여 바이트를 처리 해야 할 수 있습니다. 이 경우 호출 간의 상태를 유지 해야 합니다.

  • 앱에서 문자열 출력을 처리 하는 경우 메서드를 사용 하는 것이 좋습니다 GetString . 이 메서드는 문자열 길이를 확인 하 고 버퍼를 할당 해야 하므로 약간 더 느리지만 결과 String 형식을 선호 합니다.

  • 바이트 버전의에서는 GetChars(Byte*, Int32, Char*, Int32) 특히 대량 버퍼를 여러 번 호출 하 여 몇 가지 빠른 기술을 사용할 수 있습니다. 그러나 포인터가 필요 하므로이 메서드 버전은 안전 하지 않을 수도 있습니다.

  • 앱이 많은 양의 데이터를 변환 해야 하는 경우 출력 버퍼를 다시 사용 해야 합니다. 이 경우 GetChars(Byte[], Int32, Int32, Char[], Int32) 출력 문자 버퍼를 지 원하는 버전을 선택 하는 것이 가장 좋습니다.

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

추가 정보

적용 대상