UTF32Encoding.GetPreamble 메서드

정의

UTF32Encoding 개체가 제공하도록 구성된 경우 UTF-32 형식으로 인코딩된 유니코드 바이트 순서 표시를 반환합니다.

public:
 override cli::array <System::Byte> ^ GetPreamble();
public override byte[] GetPreamble ();
override this.GetPreamble : unit -> byte[]
Public Overrides Function GetPreamble () As Byte()

반환

Byte[]

UTF32Encoding 개체가 제공하도록 구성된 경우 유니코드 바이트 순서 표시가 포함된 바이트 배열입니다. 그렇지 않으면 이 메서드는 길이가 0인 바이트 배열을 반환합니다.

예제

다음 코드 예제에서는 검색 하 고 다른 UTF32Encoding 인스턴스에 대 한 바이트 순서 표시를 표시 합니다.

using namespace System;
using namespace System::Text;

void PrintHexBytes( array<Byte>^bytes );

int main()
{
   
   // Create instances of UTF32Encoding, with the byte order mark and without.
   UTF32Encoding ^ u32LeNone = gcnew UTF32Encoding;
   UTF32Encoding ^ u32BeNone = gcnew UTF32Encoding( true,false );
   UTF32Encoding ^ u32LeBom = gcnew UTF32Encoding( false,true );
   UTF32Encoding ^ u32BeBom = gcnew UTF32Encoding( true,true );
   
   // Display the preamble for each instance.
   PrintHexBytes( u32LeNone->GetPreamble() );
   PrintHexBytes( u32BeNone->GetPreamble() );
   PrintHexBytes( u32LeBom->GetPreamble() );
   PrintHexBytes( u32BeBom->GetPreamble() );
}

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 example displays the following output:
      FF FE 00 00
      <none>
      FF FE 00 00
      00 00 FE FF
*/
using System;
using System.Text;

public class SamplesUTF32Encoding
{
   public static void Main()
   {
      // Create instances of UTF32Encoding, with the byte order mark and without.
      UTF32Encoding u32LeNone = new UTF32Encoding();
      UTF32Encoding u32BeNone = new UTF32Encoding( true, false );
      UTF32Encoding u32LeBom  = new UTF32Encoding( false, true );
      UTF32Encoding u32BeBom  = new UTF32Encoding( true, true );

      // Display the preamble for each instance.
      PrintHexBytes( u32LeNone.GetPreamble() );
      PrintHexBytes( u32BeNone.GetPreamble() );
      PrintHexBytes( u32LeBom.GetPreamble() );
      PrintHexBytes( u32BeBom.GetPreamble() );
   }

   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 example displays the following output.
      FF FE 00 00
      <none>
      FF FE 00 00
      00 00 FE FF
*/
Imports System.Text

Public Class SamplesUTF32Encoding   
   Public Shared Sub Main()
      ' Create instances of UTF32Encoding, with the byte order mark and without.
      Dim u32LeNone As New UTF32Encoding()
      Dim u32BeNone As New UTF32Encoding(True, False)
      Dim u32LeBom As New UTF32Encoding(False, True)
      Dim u32BeBom As New UTF32Encoding(True, True)

      ' Display the preamble for each instance.
      PrintHexBytes(u32LeNone.GetPreamble())
      PrintHexBytes(u32BeNone.GetPreamble())
      PrintHexBytes(u32LeBom.GetPreamble())
      PrintHexBytes(u32BeBom.GetPreamble())
   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 example displays the following output:
'       FF FE 00 00
'       FF FE 00 00
'       00 00 FE FF

다음 예제에서는 두 개체 UTF32Encoding 를 인스턴스화합니다. 그 중 첫 번째는 BOM을 제공하지 않고 두 번째 개체는 이 개체를 제공합니다. 그런 다음 메서드를 GetPreamble 호출하여 UTF-32로 인코딩된 문자열을 작성하기 전에 파일에 BOM을 씁니다. 예제의 출력과 같이 두 번째 인코더의 바이트를 저장하는 파일에는 첫 번째 바이트가 4바이트 더 있습니다.

using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      String s = "This is a string to write to a file using UTF-32 encoding.";

      // Write a file using the default constructor without a BOM.
      var enc = new UTF32Encoding(! BitConverter.IsLittleEndian, false);
      Byte[] bytes = enc.GetBytes(s);
      WriteToFile(@".\NoPreamble.txt", enc, bytes);

      // Use BOM.
      enc = new UTF32Encoding(! BitConverter.IsLittleEndian, true);
      WriteToFile(@".\Preamble.txt", enc, bytes);
   }

   private static void WriteToFile(String fn, Encoding enc, Byte[] bytes)
   {
      var fs = new FileStream(fn, FileMode.Create);
      Byte[] preamble = enc.GetPreamble();
      fs.Write(preamble, 0, preamble.Length);
      Console.WriteLine("Preamble has {0} bytes", preamble.Length);
      fs.Write(bytes, 0, bytes.Length);
      Console.WriteLine("Wrote {0} bytes to {1}.", fs.Length, fn);
      fs.Close();
      Console.WriteLine();
   }
}
// The example displays the following output:
//       Preamble has 0 bytes
//       Wrote 232 bytes to .\NoPreamble.txt.
//
//       Preamble has 4 bytes
//       Wrote 236 bytes to .\Preamble.txt.
Imports System.IO
Imports System.Text

Module Example
   Public Sub Main()
      Dim s As String = "This is a string to write to a file using UTF-32 encoding."
      
      ' Write a file using the default constructor without a BOM.
      Dim enc As New UTF32Encoding(Not BitConverter.IsLittleEndian, False)
      Dim bytes() As Byte = enc.GetBytes(s)
      WriteToFile("NoPreamble.txt", enc, bytes)

      ' Use BOM.
      enc = New UTF32Encoding(Not BitConverter.IsLittleEndian, True)
      WriteToFile("Preamble.txt", enc, bytes)
   End Sub

   Private Sub WriteToFile(fn As String, enc As Encoding, bytes As Byte())
      Dim fs As New FileStream(fn, FileMode.Create)
      Dim preamble() As Byte = enc.GetPreamble()
      fs.Write(preamble, 0, preamble.Length)
      Console.WriteLine("Preamble has {0} bytes", preamble.Length)
      fs.Write(bytes, 0, bytes.Length)
      Console.WriteLine("Wrote {0} bytes to {1}.", fs.Length, fn)
      fs.Close()
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'       Preamble has 0 bytes
'       Wrote 232 bytes to NoPreamble.txt.
'
'       Preamble has 4 bytes
'       Wrote 236 bytes to Preamble.txt.

콘솔 창에서 명령을 사용하여 fc 파일을 비교하거나 16진수 보기 모드가 포함된 텍스트 편집기에서 파일을 검사할 수도 있습니다. UTF-32를 지원하는 편집기에서 파일을 열면 BOM이 표시되지 않습니다.

설명

개체는 UTF32Encoding 인코딩 프로세스에서 발생하는 바이트 시퀀스에 접두사를 지정할 수 있는 바이트 배열인 프리앰블을 제공할 수 있습니다. 바이트 순서 표시(코드 포인트 U+0000 U+FEFF)를 사용하여 인코딩된 바이트 시퀀스를 앞에 추가하면 디코더가 바이트 순서와 변환 형식 또는 UTF를 결정하는 데 도움이 됩니다. 유니코드 바이트 순서 표시 (BOM)는 다음과 같이 serialize 됩니다 (16 진수).

  • 빅 엔디안 바이트 순서: 00 00 FE FF

  • Little endian 바이트 순서: FF FE 00 00

메서드가 UTF32Encoding 다음과 같은 방법으로 유효한 BOM을 반환하는 개체 GetPreamble 를 인스턴스화할 수 있습니다.

BOM은 개체에 대한 참조 UTF32Encoding 가 손실된 파일(예: 태그가 지정되지 않거나 부적절하게 태그가 지정된 웹 데이터 또는 비즈니스에 국제적인 문제 또는 기타 데이터가 없을 때 저장된 임의 텍스트 파일)에 대한 인코딩의 거의 특정 ID를 제공하기 때문에 BOM을 사용하는 것이 좋습니다. 데이터가 일관되고 적절하게 태그가 지정된 경우 사용자 문제를 방지할 수 있는 경우가 많습니다.

인코딩 유형을 제공 하는 표준의 경우 BOM은 다소 중복 됩니다. 그러나 서버에서 올바른 인코딩 헤더를 보내는 데 사용할 수 있습니다. 또는 인코딩이 손실 되는 경우 대체 방법으로 사용할 수 있습니다.

BOM을 사용 하는 경우 몇 가지 단점이 있습니다. 예를 들어 BOM을 사용 하는 데이터베이스 필드를 제한 하는 방법을 알고 있는 것은 어려울 수 있습니다. 파일의 연결은 예를 들어 불필요 한 문자가 데이터 중간에 종료 될 수 있는 방식으로 파일을 병합 하는 경우에도 문제가 될 수 있습니다. 그러나 몇 가지 단점에도 불구 하 고 BOM을 사용 하는 것이 좋습니다.

바이트 순서 및 바이트 순서 표시에 대 한 자세한 내용은 유니코드 홈페이지에서 유니코드 표준을 참조 하세요.

중요

인코딩된 바이트가 올바르게 디코딩 되도록 하려면 인코딩된 바이트를 프리앰블을 접두사로 사용 해야 합니다. 메서드는 GetBytes 인코딩된 바이트 시퀀스에 BOM 앞에 추가되지 않습니다. 적절한 바이트 스트림의 시작 부분에 BOM을 제공하는 것은 개발자의 책임입니다.

적용 대상