UTF32Encoding.GetString(Byte[], Int32, Int32) Méthode

Définition

Décode une plage d'octets d'un tableau d'octets en une chaîne.

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

Paramètres

bytes
Byte[]

Tableau d'octets contenant la séquence d'octets à décoder.

index
Int32

Index du premier octet à décoder.

count
Int32

Nombre d'octets à décoder.

Retours

String

Chaîne contenant les résultats du décodage de la séquence d'octets spécifiée.

Exceptions

bytes a la valeur null.

index ou count est inférieur à zéro.

  • ou - index et count ne désignent pas une plage valide dans bytes.

La détection d’erreurs est activée et bytes contient une séquence d’octets non valide.

Une secours s’est produite (pour plus d’informations, consultez Encodage de caractères dans .NET pour obtenir une explication complète).

-et- DecoderFallback a la valeur DecoderExceptionFallback.

Exemples

L’exemple suivant encode une chaîne en deux tableaux d’octets, un dans l’ordre little-endian et l’autre dans l’ordre big-endian. Il décode ensuite les octets dans une chaîne.

using System;
using System.Text;

public class Example  
{
   public static void Main()  
   {
      // Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      UTF32Encoding u32LE = new UTF32Encoding(false, true, true);
      UTF32Encoding u32BE = new UTF32Encoding(true, true, true);

      // Create byte arrays from the same string containing the following characters:
      //    Latin Small Letter Z (U+007A)
      //    Latin Small Letter A (U+0061)
      //    Combining Breve (U+0306)
      //    Latin Small Letter AE With Acute (U+01FD)
      //    Greek Small Letter Beta (U+03B2)
      String str = "za\u0306\u01FD\u03B2";

      // barrBE uses the big-endian byte order.
      byte[] barrBE = new byte[u32BE.GetByteCount(str)];
      u32BE.GetBytes(str, 0, str.Length, barrBE, 0);

      // barrLE uses the little-endian byte order.
      byte[] barrLE = new byte[u32LE.GetByteCount(str)];
      u32LE.GetBytes(str, 0, str.Length, barrLE, 0);

      // Decode the byte arrays.
      Console.WriteLine("BE array with BE encoding:");
      DisplayString(barrBE, u32BE);
      Console.WriteLine();

      Console.WriteLine("LE array with LE encoding:");
      DisplayString(barrLE, u32LE);
      Console.WriteLine();
   
      // Decode the byte arrays using an encoding with a different byte order.
      Console.WriteLine("BE array with LE encoding:");
      try  {
         DisplayString(barrBE, u32LE);
      }
      catch (System.ArgumentException e)  {
         Console.WriteLine(e.Message);
      }
      Console.WriteLine();

      Console.WriteLine("LE array with BE encoding:");
      try  {
         DisplayString(barrLE, u32BE);
      }
      catch (ArgumentException e)  {
         Console.WriteLine(e.Message);
      }
      Console.WriteLine();
   }

   public static void DisplayString(byte[] bytes, Encoding enc)  
   {
      // Display the name of the encoding used.
      Console.Write("{0,-25}: ", enc.ToString());

      // Decode the bytes and display the characters.
      Console.WriteLine(enc.GetString(bytes, 0, bytes.Length));
   }
}
// This example displays the following output:
//   BE array with BE encoding:
//   System.Text.UTF32Encoding: zăǽβ
//
//   LE array with LE encoding:
//   System.Text.UTF32Encoding: zăǽβ
//
//   BE array with LE encoding:
//   System.Text.UTF32Encoding: Unable to translate bytes [00][00][00][7A] at index 0 from specified code page to Unicode.
//
//   LE array with BE encoding:
//   System.Text.UTF32Encoding: Unable to translate bytes [7A][00][00][00] at index 0 from specified code page to Unicode.
Imports System.Text

Public Module Example  
   Public Sub Main()  
      ' Create two instances of UTF32Encoding: one with little-endian byte order and one with big-endian byte order.
      Dim u32LE As New UTF32Encoding(False, True, True)
      Dim u32BE As New UTF32Encoding(True, True, True)

      ' Create byte arrays from the same string containing the following characters:
      '    Latin Small Letter Z (U+007A)
      '    Latin Small Letter A (U+0061)
      '    Combining Breve (U+0306)
      '    Latin Small Letter AE With Acute (U+01FD)
      '    Greek Small Letter Beta (U+03B2)
      Dim str As String = "za" + ChrW(&h0306) + ChrW(&h01FD) + ChrW(&h03B2)

      ' barrBE uses the big-endian byte order.
      Dim barrBE(u32BE.GetByteCount(str) - 1) As Byte
      u32BE.GetBytes(str, 0, str.Length, barrBE, 0)

      ' barrLE uses the little-endian byte order.
      Dim barrLE(u32LE.GetByteCount(str) - 1) As Byte
      u32LE.GetBytes(str, 0, str.Length, barrLE, 0)

      ' Decode the byte arrays.
      Console.WriteLine("BE array with BE encoding:")
      DisplayString(barrBE, u32BE)
      Console.WriteLine()

      Console.WriteLine("LE array with LE encoding:")
      DisplayString(barrLE, u32LE)
      Console.WriteLine()
   
      ' Decode the byte arrays using an encoding with a different byte order.
      Console.WriteLine("BE array with LE encoding:")
      Try  
         DisplayString(barrBE, u32LE)
      Catch e As ArgumentException
         Console.WriteLine(e.Message)
      End Try
      Console.WriteLine()

      Console.WriteLine("LE array with BE encoding:")
      Try  
         DisplayString(barrLE, u32BE)
      Catch e As ArgumentException
         Console.WriteLine(e.Message)
      End Try
      Console.WriteLine()
   End Sub

   Public Sub DisplayString(bytes As Byte(), enc As Encoding )  
      ' Display the name of the encoding used.
      Console.Write("{0,-25}: ", enc.ToString())

      ' Decode the bytes and display the characters.
      Console.WriteLine(enc.GetString(bytes, 0, bytes.Length))
   End Sub
End Module
' This example displays the following output:
'   BE array with BE encoding:
'   System.Text.UTF32Encoding: zăǽβ
'
'   LE array with LE encoding:
'   System.Text.UTF32Encoding: zăǽβ
'
'   BE array with LE encoding:
'   System.Text.UTF32Encoding: Unable to translate bytes [00][00][00][7A] at index 0 from specified code page to Unicode.
'
'   LE array with BE encoding:
'   System.Text.UTF32Encoding: Unable to translate bytes [7A][00][00][00] at index 0 from specified code page to Unicode.

L’exemple suivant initialise un tableau en appelant la GetByteCount méthode pour déterminer exactement le nombre d’octets requis pour une chaîne encodée, puis en ajoutant la taille de la marque d’ordre d’octet (BOM). L’exemple appelle ensuite la GetPreamble méthode pour stocker le boM dans le tableau avant d’appeler la GetBytes méthode pour stocker les octets encodés dans le tableau. L’exemple appelle ensuite la GetString méthode pour décoder la chaîne.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      var utf32 = new UTF32Encoding(! BitConverter.IsLittleEndian, true);

      String s = "It was the best of times, it was the worst of times...";

      // We need to dimension the array, since we'll populate it with 2 method calls.
      Byte[] bytes = new Byte[utf32.GetByteCount(s) + utf32.GetPreamble().Length];
      // Encode the string.
      Array.Copy(utf32.GetPreamble(), bytes, utf32.GetPreamble().Length);
      utf32.GetBytes(s, 0, s.Length, bytes, utf32.GetPreamble().Length);

      // Decode the byte array.
      String s2 = utf32.GetString(bytes, 0, bytes.Length);
      Console.WriteLine(s2);
   }
}
// The example displays the following output:
//        ?It was the best of times, it was the worst of times...
Imports System.Text

Module Example
   Public Sub Main()
      Dim utf32 As New UTF32Encoding(Not BitConverter.IsLittleEndian, True)

      Dim s As String = "It was the best of times, it was the worst of times..."

      ' We need to dimension the array, since we'll populate it with 2 method calls.
      Dim bytes(utf32.GetByteCount(s) + utf32.GetPreamble().Length - 1) As Byte
      ' Encode the string.
      Array.Copy(utf32.GetPreamble(), bytes, utf32.GetPreamble().Length)
      utf32.GetBytes(s, 0, s.Length, bytes, utf32.GetPreamble().Length)

      ' Decode the byte array.
      Dim s2 As String = utf32.GetString(bytes, 0, bytes.Length)
      Console.WriteLine(s2)
   End Sub
End Module
' The example displays the following output:
'       ?It was the best of times, it was the worst of times...

Notez que dans ce cas, la chaîne décodée diffère de la chaîne d’origine, car elle commence par une marque d’ordre d’octet 32 bits U+FFFE U+0000. Cela signifie que les deux chaînes seront comparées comme inégales et que si la chaîne est en sortie, la marque d’ordre s’affichera comme caractère de remplacement « ? ».

Remarques

Avec la détection d’erreur, une séquence non valide entraîne la levée d’une ArgumentExceptionméthode . Sans détection d’erreur, les séquences non valides sont ignorées et aucune exception n’est levée.

Si la plage d’octets à décoder inclut la marque d’ordre d’octets (BOM) et que le tableau d’octets a été retourné par une méthode d’un type sans prise en compte boM, le caractère U+FFFE est inclus dans le tableau de caractères retourné par cette méthode. Vous pouvez le supprimer en appelant la String.TrimStart méthode.

Les données à convertir, telles que les données lues à partir d’un flux, peuvent être disponibles uniquement dans des blocs séquentiels. Dans ce cas, ou si la quantité de données est si importante qu’elle doit être divisée en blocs plus petits, l’application doit utiliser respectivement la Decoder GetDecoder méthode ou GetEncoder la Encoder méthode fournie.

S’applique à

Voir aussi