Encoding.GetBytes Methode

Definition

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen in eine Bytefolge codiert.

Überlädt

GetBytes(Char[])

Beim Überschreiben in einer abgeleiteten Klasse werden alle Zeichen im angegebenen Zeichenarray in eine Bytefolge codiert.

GetBytes(String)

Beim Überschreiben in einer abgeleiteten Klasse werden alle Zeichen in der angegebenen Zeichenfolge in eine Bytefolge codiert.

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

Codiert beim Überschreiben in einer abgeleiteten Klasse eine Gruppe von Zeichen aus der angegebenen schreibgeschützten Spanne in eine Bytespanne.

GetBytes(Char[], Int32, Int32)

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen im angegebenen Zeichenarray in eine Bytefolge codiert.

GetBytes(String, Int32, Int32)

Codiert beim Überschreiben in einer abgeleiteten Klasse die Anzahl der Zeichen, die durch count in der angegebenen Zeichenfolge angegeben werden, ab dem angegebenen index in ein Bytearray.

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

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen beginnend am angegebenen Zeichenzeiger in eine Bytefolge codiert, die ab Beginn des angegebenen Bytezeigers gespeichert wird.

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

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen aus dem angegebenen Zeichenarray in das angegebene Bytearray codiert.

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

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen aus der angegebenen Zeichenfolge in das angegebene Bytearray codiert.

GetBytes(Char[])

Beim Überschreiben in einer abgeleiteten Klasse werden alle Zeichen im angegebenen Zeichenarray in eine Bytefolge codiert.

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()

Parameter

chars
Char[]

Das Zeichenarray mit den zu codierenden Zeichen.

Gibt zurück

Byte[]

Ein Bytearray mit den Ergebnissen der Codierung der angegebenen Zeichen.

Ausnahmen

chars ist null.

Es ist ein Fallback aufgetreten (weitere Informationen finden Sie unter Zeichencodierung in .NET).

- und -

Für EncoderFallback ist EncoderExceptionFallback festgelegt.

Beispiele

Im folgenden Beispiel wird die Anzahl der Bytes bestimmt, die zum Codieren eines Zeichen Arrays erforderlich sind, die Zeichen codiert und die resultierenden Bytes angezeigt werden.

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

Hinweise

Wenn die zu konvertierenden Daten nur in sequenziellen Blöcken (z. b. aus einem Stream gelesene Daten) verfügbar sind, oder wenn die Menge der Daten so groß ist, dass Sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie den Decoder oder den bereitstellen, der Encoder von der- GetDecoder Methode bzw. der- GetEncoder Methode der abgeleiteten Klasse bereitgestellt wird.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzzeichenpaare enthält, mit einem hohen Ersatzzeichen enden. Der Encoder wird sich dieses hohe Ersatzzeichen merken, sodass es am Anfang eines folgenden Aufrufs mit einem niedrigen Ersatzzeichen kombiniert werden kann. Encoding kann den Zustand nicht beibehalten, sodass das Zeichen an den EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version der-Methode aufzurufen GetBytes .

  • Die Unicode-Zeichen Puffer Version von GetBytes(Char*, Int32, Byte*, Int32) ermöglicht einige schnelle Techniken, insbesondere bei mehreren aufrufen, die das-Objekt verwenden, Encoder oder beim Einfügen in vorhandene Puffer. Beachten Sie jedoch, dass diese Methoden Version manchmal unsicher ist, da Zeiger erforderlich sind.

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Weitere Informationen

Gilt für:

GetBytes(String)

Beim Überschreiben in einer abgeleiteten Klasse werden alle Zeichen in der angegebenen Zeichenfolge in eine Bytefolge codiert.

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()

Parameter

s
String

Die Zeichenfolge mit den zu codierenden Zeichen.

Gibt zurück

Byte[]

Ein Bytearray mit den Ergebnissen der Codierung der angegebenen Zeichen.

Ausnahmen

s ist null.

Es ist ein Fallback aufgetreten (weitere Informationen finden Sie unter Zeichencodierung in .NET).

- und -

Für EncoderFallback ist EncoderExceptionFallback festgelegt.

Beispiele

Im folgenden Beispiel wird die Anzahl der Bytes festgelegt, die erforderlich sind, um eine Zeichenfolge oder einen Bereich in der Zeichenfolge zu codieren, die Zeichen codiert und die resultierenden Bytes anzeigt.

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

Hinweise

Wenn die zu konvertierenden Daten nur in sequenziellen Blöcken (z. b. aus einem Stream gelesene Daten) verfügbar sind, oder wenn die Menge der Daten so groß ist, dass Sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie den Decoder oder den bereitstellen, der Encoder von der- GetDecoder Methode bzw. der- GetEncoder Methode der abgeleiteten Klasse bereitgestellt wird.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- Encoding.GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzzeichenpaare enthält, mit einem hohen Ersatzzeichen enden. Der Encoder wird sich dieses hohe Ersatzzeichen merken, sodass es am Anfang eines folgenden Aufrufs mit einem niedrigen Ersatzzeichen kombiniert werden kann. Encoding kann den Zustand nicht beibehalten, sodass das Zeichen an den EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version von verwenden GetBytes .

  • Die Unicode-Zeichen Puffer Version von GetBytes(Char*, Int32, Byte*, Int32) ermöglicht einige schnelle Techniken, insbesondere bei mehreren aufrufen, die das-Objekt verwenden, Encoder oder beim Einfügen in vorhandene Puffer. Beachten Sie jedoch, dass diese Methoden Version manchmal unsicher ist, da Zeiger erforderlich sind.

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Weitere Informationen

Gilt für:

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

Codiert beim Überschreiben in einer abgeleiteten Klasse eine Gruppe von Zeichen aus der angegebenen schreibgeschützten Spanne in eine Bytespanne.

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

Parameter

chars
ReadOnlySpan<Char>

Die Spanne mit den zu codierenden Zeichen.

bytes
Span<Byte>

Die Bytespanne, die die codierten Bytes enthalten soll.

Gibt zurück

Die Anzahl der codierten Bytes.

Hinweise

Wenn die zu konvertierenden Daten nur in sequenziellen Blöcken (z. b. aus einem Stream gelesene Daten) verfügbar sind, oder wenn die Menge der Daten so groß ist, dass Sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie den Decoder oder den bereitstellen, der Encoder von der- GetDecoder Methode bzw. der- GetEncoder Methode der abgeleiteten Klasse bereitgestellt wird.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- Encoding.GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzzeichenpaare enthält, mit einem hohen Ersatzzeichen enden. Der Encoder wird sich dieses hohe Ersatzzeichen merken, sodass es am Anfang eines folgenden Aufrufs mit einem niedrigen Ersatzzeichen kombiniert werden kann. Encoding kann den Zustand nicht beibehalten, sodass das Zeichen an den EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version von verwenden GetBytes .

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Gilt für:

GetBytes(Char[], Int32, Int32)

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen im angegebenen Zeichenarray in eine Bytefolge codiert.

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()

Parameter

chars
Char[]

Das Zeichenarray, das die zu codierenden Zeichen enthält.

index
Int32

Der Index des ersten zu codierenden Zeichens.

count
Int32

Die Anzahl der zu codierenden Zeichen.

Gibt zurück

Byte[]

Ein Bytearray mit den Ergebnissen der Codierung der angegebenen Zeichen.

Ausnahmen

chars ist null.

index oder count ist kleiner als 0.

- oder -

index und count geben keinen gültigen Bereich in chars an.

Es ist ein Fallback aufgetreten (weitere Informationen finden Sie unter Zeichencodierung in .NET).

- und -

Für EncoderFallback ist EncoderExceptionFallback festgelegt.

Beispiele

Im folgenden Beispiel wird die Anzahl der Bytes festgelegt, die erforderlich sind, um drei Zeichen aus einem Zeichen Array zu codieren, die Zeichen zu codieren und die resultierenden Bytes anzeigen.

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

Hinweise

Wenn die zu konvertierenden Daten nur in sequenziellen Blöcken (z. b. aus einem Stream gelesene Daten) verfügbar sind, oder wenn die Menge der Daten so groß ist, dass Sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie den Decoder oder den bereitstellen, der Encoder von der- GetDecoder Methode bzw. der- GetEncoder Methode der abgeleiteten Klasse bereitgestellt wird.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- Encoding.GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzpaare enthält, mit einem hohen Ersatzwert enden. Der Encoder wird sich an diesen hohen Ersatz erinnern, sodass es mit einem niedrigen Ersatz zu Beginn eines folgenden Aufrufs kombiniert werden kann. Encoding wird nicht in der Lage sein, den Zustand beizubehalten, sodass das Zeichen an die EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version von verwenden GetBytes .

  • Die Unicode-Zeichen Puffer Version von GetBytes(Char*, Int32, Byte*, Int32) ermöglicht einige schnelle Techniken, insbesondere bei mehreren aufrufen, die das-Objekt verwenden, Encoder oder beim Einfügen in vorhandene Puffer. Beachten Sie jedoch, dass diese Methoden Version manchmal unsicher ist, da Zeiger erforderlich sind.

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Weitere Informationen

Gilt für:

GetBytes(String, Int32, Int32)

Codiert beim Überschreiben in einer abgeleiteten Klasse die Anzahl der Zeichen, die durch count in der angegebenen Zeichenfolge angegeben werden, ab dem angegebenen index in ein Bytearray.

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()

Parameter

s
String

Die Zeichenfolge mit den zu codierenden Zeichen.

index
Int32

Der Index in der Zeichenfolge, ab dem die Codierung beginnen soll.

count
Int32

Die Anzahl der zu codierenden Zeichen.

Gibt zurück

Byte[]

Ein Bytearray mit den Ergebnissen der Codierung der angegebenen Zeichen.

Beispiele

Im folgenden Beispiel wird die Anzahl der Bytes festgelegt, die erforderlich sind, um eine Zeichenfolge oder einen Bereich in der Zeichenfolge zu codieren, die Zeichen codiert und die resultierenden Bytes anzeigt.

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

Hinweise

Wenn die zu konvertierenden Daten nur in sequenziellen Blöcken (z. b. aus einem Stream gelesene Daten) verfügbar sind, oder wenn die Menge der Daten so groß ist, dass Sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie den Decoder oder den bereitstellen, der Encoder von der- GetDecoder Methode bzw. der- GetEncoder Methode der abgeleiteten Klasse bereitgestellt wird.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- Encoding.GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzpaare enthält, mit einem hohen Ersatzwert enden. Der Encoder wird sich an diesen hohen Ersatz erinnern, sodass es mit einem niedrigen Ersatz zu Beginn eines folgenden Aufrufs kombiniert werden kann. Encoding wird nicht in der Lage sein, den Zustand beizubehalten, sodass das Zeichen an die EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version von verwenden GetBytes .

  • Die Unicode-Zeichen Puffer Version von GetBytes(Char*, Int32, Byte*, Int32) ermöglicht einige schnelle Techniken, insbesondere bei mehreren aufrufen, die das-Objekt verwenden, Encoder oder beim Einfügen in vorhandene Puffer. Beachten Sie jedoch, dass diese Methoden Version manchmal unsicher ist, da Zeiger erforderlich sind.

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Gilt für:

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

Wichtig

Diese API ist nicht CLS-kompatibel.

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen beginnend am angegebenen Zeichenzeiger in eine Bytefolge codiert, die ab Beginn des angegebenen Bytezeigers gespeichert wird.

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);
[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
[<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

Parameter

chars
Char*

Ein Zeiger auf das erste zu codierende Zeichen.

charCount
Int32

Die Anzahl der zu codierenden Zeichen.

bytes
Byte*

Ein Zeiger auf die Position, an der mit dem Schreiben der sich ergebenden Bytefolge begonnen werden soll.

byteCount
Int32

Die maximale Anzahl der zu schreibenden Bytes.

Gibt zurück

Die tatsächliche Anzahl an Bytes, die an der durch den bytes-Parameter angegebenen Position geschrieben wurden.

Attribute

Ausnahmen

chars ist null.

- oder -

bytes ist null.

charCount oder byteCount ist kleiner als 0.

byteCount ist niedriger als die sich ergebende Anzahl von Bytes.

Es ist ein Fallback aufgetreten (weitere Informationen finden Sie unter Zeichencodierung in .NET).

- und -

Für EncoderFallback ist EncoderExceptionFallback festgelegt.

Hinweise

Um die genaue Array Größe zu berechnen, die GetBytes zum Speichern der resultierenden Bytes benötigt, wird die- GetByteCount Methode aufgerufen. Um die maximale Array Größe zu berechnen, müssen Sie die-Methode aufzurufen GetMaxByteCount . Die- GetByteCount Methode ermöglicht im Allgemeinen die Zuordnung von weniger Arbeitsspeicher, während die- GetMaxByteCount Methode im Allgemeinen schneller ausgeführt wird.

Wenn die zu konvertierenden Daten nur in sequenzielle Blöcke (z. B. aus einem Stream gelesene Daten) verfügbar ist oder wenn die Menge der Daten so groß, dass sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie mit ist der Decoder oder die Encoder Objekt von der bereitgestellten GetDecoder oder GetEncoder -Methode, von einer abgeleiteten Klasse.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzpaare enthält, mit einem hohen Ersatzwert enden. Der Encoder wird sich an diesen hohen Ersatz erinnern, sodass es mit einem niedrigen Ersatz zu Beginn eines folgenden Aufrufs kombiniert werden kann. Encoding wird nicht in der Lage sein, den Zustand beizubehalten, sodass das Zeichen an die EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version von verwenden GetBytes .

  • Die Unicode-Zeichen Puffer Version von GetBytes(Char*, Int32, Byte*, Int32) ermöglicht einige schnelle Techniken, insbesondere bei mehreren aufrufen, die das-Objekt verwenden, Encoder oder beim Einfügen in vorhandene Puffer. Beachten Sie jedoch, dass diese Methoden Version manchmal unsicher ist, da Zeiger erforderlich sind.

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Weitere Informationen

Gilt für:

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

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen aus dem angegebenen Zeichenarray in das angegebene Bytearray codiert.

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

Parameter

chars
Char[]

Das Zeichenarray, das die zu codierenden Zeichen enthält.

charIndex
Int32

Der Index des ersten zu codierenden Zeichens.

charCount
Int32

Die Anzahl der zu codierenden Zeichen.

bytes
Byte[]

Das Bytearray, das die sich ergebende Bytefolge enthalten soll.

byteIndex
Int32

Der Index, an dem mit dem Schreiben der sich ergebenden Bytefolge begonnen werden soll.

Gibt zurück

Die tatsächliche Anzahl der Bytes, die in bytes geschrieben werden.

Ausnahmen

chars ist null.

- oder -

bytes ist null.

charIndex, charCount oder byteIndex ist kleiner als 0 (null).

- oder -

charIndex und charCount geben keinen gültigen Bereich in charsan.

- oder -

byteIndex ist kein gültiger Index in bytes.

bytes hat von byteIndex bis zum Ende des Arrays nicht genügend Kapazität, um die sich ergebenden Bytes aufzunehmen.

Es ist ein Fallback aufgetreten (weitere Informationen finden Sie unter Zeichencodierung in .NET).

- und -

Für EncoderFallback ist EncoderExceptionFallback festgelegt.

Beispiele

Im folgenden Beispiel wird die Anzahl der Bytes festgelegt, die erforderlich sind, um drei Zeichen aus einem Zeichen Array zu codieren, die Zeichen zu codieren und die resultierenden Bytes anzeigen.

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

Hinweise

Zum Berechnen der exakten Array Größe, die von GetBytes zum Speichern der resultierenden Bytes benötigt wird, sollten Sie die-Methode aufzurufen GetByteCount . Um die maximale Array Größe zu berechnen, müssen Sie die-Methode aufzurufen GetMaxByteCount . Die- GetByteCount Methode ermöglicht im Allgemeinen die Zuordnung von weniger Arbeitsspeicher, während die- GetMaxByteCount Methode im Allgemeinen schneller ausgeführt wird.

Wenn die zu konvertierenden Daten nur in sequenziellen Blöcken (z. b. aus einem Stream gelesene Daten) verfügbar sind, oder wenn die Menge der Daten so groß ist, dass Sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie den Decoder oder den bereitstellen, der Encoder von der- GetDecoder Methode bzw. der- GetEncoder Methode der abgeleiteten Klasse bereitgestellt wird.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- Encoding.GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzpaare enthält, mit einem hohen Ersatzwert enden. Der Encoder wird sich an diesen hohen Ersatz erinnern, sodass es mit einem niedrigen Ersatz zu Beginn eines folgenden Aufrufs kombiniert werden kann. Encoding wird nicht in der Lage sein, den Zustand beizubehalten, sodass das Zeichen an die EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version von verwenden GetBytes .

  • Die Unicode-Zeichen Puffer Version von GetBytes(Char*, Int32, Byte*, Int32) ermöglicht einige schnelle Techniken, insbesondere bei mehreren aufrufen, die das-Objekt verwenden, Encoder oder beim Einfügen in vorhandene Puffer. Beachten Sie jedoch, dass diese Methoden Version manchmal unsicher ist, da Zeiger erforderlich sind.

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Weitere Informationen

Gilt für:

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

Beim Überschreiben in einer abgeleiteten Klasse werden die Zeichen aus der angegebenen Zeichenfolge in das angegebene Bytearray codiert.

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

Parameter

s
String

Die Zeichenfolge mit den zu codierenden Zeichen.

charIndex
Int32

Der Index des ersten zu codierenden Zeichens.

charCount
Int32

Die Anzahl der zu codierenden Zeichen.

bytes
Byte[]

Das Bytearray, das die sich ergebende Bytefolge enthalten soll.

byteIndex
Int32

Der Index, an dem mit dem Schreiben der sich ergebenden Bytefolge begonnen werden soll.

Gibt zurück

Die tatsächliche Anzahl der Bytes, die in bytes geschrieben werden.

Ausnahmen

s ist null.

- oder -

bytes ist null.

charIndex, charCount oder byteIndex ist kleiner als 0 (null).

- oder -

charIndex und charCount geben keinen gültigen Bereich in charsan.

- oder -

byteIndex ist kein gültiger Index in bytes.

bytes hat von byteIndex bis zum Ende des Arrays nicht genügend Kapazität, um die sich ergebenden Bytes aufzunehmen.

Es ist ein Fallback aufgetreten (weitere Informationen finden Sie unter Zeichencodierung in .NET).

- und -

Für EncoderFallback ist EncoderExceptionFallback festgelegt.

Beispiele

Im folgenden Beispiel wird die Anzahl der Bytes festgelegt, die erforderlich sind, um eine Zeichenfolge oder einen Bereich in der Zeichenfolge zu codieren, die Zeichen codiert und die resultierenden Bytes anzeigt.

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

Hinweise

Zum Berechnen der exakten Array Größe, die von GetBytes zum Speichern der resultierenden Bytes benötigt wird, sollten Sie die-Methode aufzurufen GetByteCount . Um die maximale Array Größe zu berechnen, müssen Sie die-Methode aufzurufen GetMaxByteCount . Die- GetByteCount Methode ermöglicht im Allgemeinen die Zuordnung von weniger Arbeitsspeicher, während die- GetMaxByteCount Methode im Allgemeinen schneller ausgeführt wird.

Wenn die zu konvertierenden Daten nur in sequenziellen Blöcken (z. b. aus einem Stream gelesene Daten) verfügbar sind, oder wenn die Menge der Daten so groß ist, dass Sie in kleinere Blöcke aufgeteilt werden muss, sollten Sie den Decoder oder den bereitstellen, der Encoder von der- GetDecoder Methode bzw. der- GetEncoder Methode der abgeleiteten Klasse bereitgestellt wird.

Die GetByteCount -Methode bestimmt, wie viele Bytes zum Codieren eines Satzes von Unicode-Zeichen führen, und die- GetBytes Methode führt die eigentliche Codierung aus. Die- Encoding.GetBytes Methode erwartet diskrete Konvertierungen, im Gegensatz zur- Encoder.GetBytes Methode, die mehrere Konvertierungen für einen einzelnen Eingabestream verarbeitet.

Es werden mehrere Versionen von GetByteCount und GetBytes unterstützt. Im folgenden finden Sie einige Überlegungen zur Programmierung bei der Verwendung dieser Methoden:

  • Möglicherweise muss Ihre APP viele Eingabezeichen in eine Codepage codieren und die Zeichen mithilfe mehrerer Aufrufe verarbeiten. In diesem Fall müssen Sie möglicherweise den Status zwischen den Aufrufen beibehalten und dabei den Zustand berücksichtigen, der von dem verwendeten Objekt persistent gespeichert wird Encoder . (Beispielsweise kann eine Zeichenfolge, die Ersatzpaare enthält, mit einem hohen Ersatzwert enden. Der Encoder wird sich an diesen hohen Ersatz erinnern, sodass es mit einem niedrigen Ersatz zu Beginn eines folgenden Aufrufs kombiniert werden kann. Encoding wird nicht in der Lage sein, den Zustand beizubehalten, sodass das Zeichen an die EncoderFallbackgesendet wird.

  • Wenn Ihre APP Zeichen folgen Eingaben behandelt, sollten Sie die Zeichen folgen Version von verwenden GetBytes .

  • Die Unicode-Zeichen Puffer Version von GetBytes(Char*, Int32, Byte*, Int32) ermöglicht einige schnelle Techniken, insbesondere bei mehreren aufrufen, die das-Objekt verwenden, Encoder oder beim Einfügen in vorhandene Puffer. Beachten Sie jedoch, dass diese Methoden Version manchmal unsicher ist, da Zeiger erforderlich sind.

  • Wenn Ihre APP eine große Datenmenge konvertieren muss, sollte Sie den Ausgabepuffer wieder verwenden. In diesem Fall ist die GetBytes Version, die Byte Arrays unterstützt, die beste Wahl.

  • Sie sollten die- Encoder.Convert Methode anstelle von verwenden GetByteCount . Die Konvertierungsmethode konvertiert so viele Daten wie möglich, und löst eine Ausnahme aus, wenn der Ausgabepuffer zu klein ist. Bei der kontinuierlichen Codierung eines Streams ist diese Methode oft die beste Wahl.

Weitere Informationen

Gilt für: