Versión imprimible       Enviar     
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
UTF32Encoding (Clase)
Representa una codificación UTF-32 de caracteres Unicode.

Espacio de nombres: System.Text
Ensamblado: mscorlib (en mscorlib.dll)

Visual Basic (Declaración)
<SerializableAttribute> _
Public NotInheritable Class UTF32Encoding
    Inherits Encoding
Visual Basic (Uso)
Dim instance As UTF32Encoding
C#
[SerializableAttribute] 
public sealed class UTF32Encoding : Encoding
C++
[SerializableAttribute] 
public ref class UTF32Encoding sealed : public Encoding
J#
/** @attribute SerializableAttribute() */ 
public final class UTF32Encoding extends Encoding
JScript
SerializableAttribute 
public final class UTF32Encoding extends Encoding
XAML
No aplicable.

Codificar es el proceso de transformar un conjunto de caracteres Unicode en una secuencia de bytes. Descodificar es el proceso inverso; es transformar una secuencia de bytes codificados en un conjunto de caracteres Unicode.

El estándar Unicode asigna un punto de código (un número) a cada carácter en todas las secuencias de comandos compatibles. Un Formato de transformación Unicode (UTF) es un método para codificar ese punto de código. El estándar Unicode versión 3.2 utiliza las siguientes codificaciones UTF:

  • UTF-8, que representa cada punto de código como una secuencia de uno a cuatro bytes.

  • UTF-16, que representa cada punto de código como una secuencia de uno a dos enteros de 16 bits.

  • UTF-32, que representa cada punto de código como un entero de 32 bits.

El método GetByteCount determina cuántos bytes resultan de codificar un conjunto de caracteres Unicode, y el método GetBytes realiza la codificación real.

Igualmente, el método GetCharCount determina el número de caracteres resultante en la descodificación de una secuencia de bytes, y los métodos GetChars y GetString realizan la descodificación real.

El codificador puede utilizar el orden de bytes big-endian (primero el byte más significativo) o el orden de bytes little-endian (primero el byte menos significativo). Por ejemplo, la letra mayúscula latina A (punto de código U+0041) se serializa del siguiente modo (en hexadecimal):

  • Orden de bytes big-endian: 00 00 00 41

  • Orden de bytes little-endian: 41 00 00 00

Opcionalmente, UTF32Encoding proporciona un preámbulo, que es una matriz de bytes que se puede anteponer a la secuencia de bytes resultante del proceso de codificación. Si el preámbulo contiene una marca de orden de bytes (punto de código U+FEFF), ayudará al descodificador a determinar el orden de bytes y el formato de la transformación o UTF. La marca de orden de bytes Unicode se serializa de la siguiente manera (en hexadecimal):

  • Orden de bytes big-endian: 00 00 FE FF

  • Orden de bytes little-endian: FF FE 00 00

Generalmente es más eficaz almacenar caracteres Unicode utilizando el orden de bytes nativo. Por ejemplo, es mejor utilizar el orden de bytes little-endian en plataformas little-endian, como los equipos Intel.

El método GetPreamble devuelve una matriz de bytes que contiene la marca de orden de bytes. Si esta matriz de bytes se antepone a una secuencia codificada, ayudará al descodificador a identificar el formato de codificación utilizado.

Para obtener más información acerca de la codificación Unicode, del orden de bytes y de la marca de orden de bytes, vea el estándar Unicode en www.unicode.org.

NotaNota:

Para habilitar la detección de errores y hacer que la instancia de clase sea más segura, utilice el constructor UTF32Encoding que toma un parámetro throwOnInvalidCharacters y establece ese parámetro en true. Con la detección de errores, el método que detecte una secuencia de caracteres o de bytes no válida producirá una excepción ArgumentException. Sin la detección de errores, no se producirá excepción alguna y, por lo general, se omitirá la secuencia no válida.

UTF32Encoding corresponde a las páginas de códigos 12000 (orden de bytes little-endian) y 12001 (orden de bytes big-endian) de Windows.

En el ejemplo de código siguiente se muestra el comportamiento de UTF32Encoding, con la detección de errores habilitada y sin habilitar.

Visual Basic
Imports System
Imports System.Text
Imports Microsoft.VisualBasic

Public Class SamplesUTF32Encoding   

   Public Shared Sub Main()

      ' Create an instance of UTF32Encoding using little-endian byte order.
      ' This will be used for encoding.
      Dim u32LE As New UTF32Encoding(False, True)

      ' Create two instances of UTF32Encoding using big-endian byte order: one with error detection and one without.
      ' These will be used for decoding.
      Dim u32withED As New UTF32Encoding(True, True, True)
      Dim u32noED As New UTF32Encoding(True, True, False)

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

      ' Encode the string using little-endian byte order.
      Dim myBytes(u32LE.GetByteCount(myStr)) As Byte
      u32LE.GetBytes(myStr, 0, myStr.Length, myBytes, 0)

      ' Decode the byte array with error detection.
      Console.WriteLine("Decoding with error detection:")
      PrintDecodedString(myBytes, u32withED)

      ' Decode the byte array without error detection.
      Console.WriteLine("Decoding without error detection:")
      PrintDecodedString(myBytes, u32noED)

   End Sub 'Main


   ' Decode the bytes and display the string.
   Public Shared Sub PrintDecodedString(bytes() As Byte, enc As Encoding)

      Try
         Console.WriteLine("   Decoded string: {0}", enc.GetString(bytes, 0, bytes.Length))
      Catch e As System.ArgumentException
         Console.WriteLine(e.ToString())
      End Try

      Console.WriteLine()

   End Sub 'PrintDecodedString 

End Class 'SamplesUTF32Encoding
C#
using System;
using System.Text;

public class SamplesUTF32Encoding  {

   public static void Main()  {

      // Create an instance of UTF32Encoding using little-endian byte order.
      // This will be used for encoding.
      UTF32Encoding u32LE     = new UTF32Encoding( false, true );

      // Create two instances of UTF32Encoding using big-endian byte order: one with error detection and one without.
      // These will be used for decoding.
      UTF32Encoding u32withED = new UTF32Encoding( true, true, true );
      UTF32Encoding u32noED   = new UTF32Encoding( true, true, false );

      // 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)
      //    a high-surrogate value (U+D8FF)
      //    a low-surrogate value (U+DCFF)
      String myStr = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";

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

      // Decode the byte array with error detection.
      Console.WriteLine( "Decoding with error detection:" );
      PrintDecodedString( myBytes, u32withED );

      // Decode the byte array without error detection.
      Console.WriteLine( "Decoding without error detection:" );
      PrintDecodedString( myBytes, u32noED );

   }


   // Decode the bytes and display the string.
   public static void PrintDecodedString( byte[] bytes, Encoding enc )  {

      try  {
         Console.WriteLine( "   Decoded string: {0}", enc.GetString( bytes, 0, bytes.Length ) );
      }
      catch ( System.ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      Console.WriteLine();

   }

}
C++
using namespace System;
using namespace System::Text;
void PrintDecodedString( array<Byte>^bytes, Encoding^ enc );
int main()
{
   
   // Create an instance of UTF32Encoding using little-endian byte order.
   // This will be used for encoding.
   UTF32Encoding^ u32LE = gcnew UTF32Encoding( false,true );
   
   // Create two instances of UTF32Encoding using big-endian byte order: one with error detection and one without.
   // These will be used for decoding.
   UTF32Encoding^ u32withED = gcnew UTF32Encoding( true,true,true );
   UTF32Encoding^ u32noED = gcnew UTF32Encoding( true,true,false );
   
   // 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^ myStr = L"za\u0306\u01FD\u03B2\xD8FF\xDCFF";
   
   // Encode the string using little-endian byte order.
   array<Byte>^myBytes = gcnew array<Byte>(u32LE->GetByteCount( myStr ));
   u32LE->GetBytes( myStr, 0, myStr->Length, myBytes, 0 );
   
   // Decode the byte array with error detection.
   Console::WriteLine( "Decoding with error detection:" );
   PrintDecodedString( myBytes, u32withED );
   
   // Decode the byte array without error detection.
   Console::WriteLine( "Decoding without error detection:" );
   PrintDecodedString( myBytes, u32noED );
}


// Decode the bytes and display the string.
void PrintDecodedString( array<Byte>^bytes, Encoding^ enc )
{
   try
   {
      Console::WriteLine( "   Decoded string: {0}", enc->GetString( bytes, 0, bytes->Length ) );
   }
   catch ( System::ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   Console::WriteLine();
}
J#
import System.*;
import System.Text.*;

public class SamplesUTF32Encoding
{
    public static void main(String[] args)
    {
        // Create an instance of UTF32Encoding using little-endian byte order.
        // This will be used for encoding.
        UTF32Encoding u32LE =  new UTF32Encoding(false, true);

        // Create two instances of UTF32Encoding using big-endian byte order: 
        // one with error detection and one without.
        // These will be used for decoding.
        UTF32Encoding u32withED =  new UTF32Encoding(true, true, true);
        UTF32Encoding u32noED =  new UTF32Encoding(true, true, false);

        // 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)
        //    a high-surrogate value (U+D8FF)
        //    a low-surrogate value (U+DCFF)
        String myStr = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";

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

        // Decode the byte array with error detection.
        Console.WriteLine("Decoding with error detection:");
        PrintDecodedString(myBytes, u32withED);

        // Decode the byte array without error detection.
        Console.WriteLine("Decoding without error detection:");
        PrintDecodedString(myBytes, u32noED);
    } //main

    // Decode the bytes and display the string.
    public static void PrintDecodedString(ubyte bytes[], Encoding enc) 
    {
        try {
            Console.WriteLine("   Decoded string: {0}",
                enc.GetString(bytes, 0, bytes.length));
        }
        catch(System.ArgumentException e) {
            Console.WriteLine(e.ToString());
        }
        Console.WriteLine();
    } //PrintDecodedString
} //SamplesUTF32Encoding
System.Object
   System.Text.Encoding
    System.Text.UTF32Encoding
Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows 98, Windows 2000 Service Pack 4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

.NET Framework

Compatible con: 3.0, 2.0
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker