UTF8Encoding.GetBytes UTF8Encoding.GetBytes UTF8Encoding.GetBytes UTF8Encoding.GetBytes Method

定義

將一組字元編碼成位元組序列。Encodes a set of characters into a sequence of bytes.

多載

GetBytes(String) GetBytes(String) GetBytes(String) GetBytes(String)

將指定 String 物件中的字元編碼成位元組序列。Encodes the characters in a specified String object into a sequence of bytes.

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

將指定的字元範圍編碼為指定的位元組範圍。Encodes the specified character span into the specified byte span.

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

將起始於指定字元指標的一組字元編碼成位元組序列;儲存該位元組序列時,係以指定的位元組指標為起始點。Encodes a set of characters starting at the specified character pointer into a sequence of bytes that are stored starting at the specified byte pointer.

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

將指定字元陣列中的一組字元編碼成指定的位元組陣列。Encodes a set of characters from the specified character array into the specified byte array.

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

將指定 String 中的一組字元編碼成指定的位元組陣列。Encodes a set of characters from the specified String into the specified byte array.

GetBytes(String) GetBytes(String) GetBytes(String) GetBytes(String)

將指定 String 物件中的字元編碼成位元組序列。Encodes the characters in a specified String object into a sequence of bytes.

public:
 override cli::array <System::Byte> ^ GetBytes(System::String ^ s);
public override byte[] GetBytes (string s);
override this.GetBytes : string -> byte[]
Public Overrides Function GetBytes (s As String) As Byte()

參數

s
String String String String

要編碼的字元字串。The character string to encode.

傳回

Byte[]

位元組陣列,包含 s 參數所指定之字串中已編碼的字元。A byte array that contains the encoded characters in the string specified by the s parameter.

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

將指定的字元範圍編碼為指定的位元組範圍。Encodes the specified character span into the specified byte span.

public:
 override int GetBytes(ReadOnlySpan<char> chars, Span<System::Byte> bytes);
public override int GetBytes (ReadOnlySpan<char> chars, Span<byte> bytes);
override this.GetBytes : ReadOnlySpan<char> * Span<byte> -> int
Public Overrides Function GetBytes (chars As ReadOnlySpan(Of Char), bytes As Span(Of Byte)) As Integer

參數

chars
ReadOnlySpan<Char>

要編碼的字元範圍。The character span to encode.

bytes
Span<Byte>

包含所產生之位元組集合的範圍。The span to contain the resulting set of bytes.

傳回

寫入 bytes 的實際位元組數。The actual number of bytes written into bytes.

備註

若要計算所需GetBytes的確切大小以儲存產生的位元組, 您可以GetByteCount呼叫方法。To calculate the exact size required by GetBytes to store the resulting bytes, you call the GetByteCount method. 若要計算大小上限, 您可以呼叫GetMaxByteCount方法。To calculate the maximum size, you call the GetMaxByteCount method. 方法通常會配置較少的GetMaxByteCount記憶體, 而方法通常會更快速地執行。 GetByteCountThe GetByteCount method generally allocates less memory, while the GetMaxByteCount method generally executes faster.

使用錯誤偵測時, 不正確順序會導致這個方法擲ArgumentException回例外狀況。With error detection, an invalid sequence causes this method to throw an ArgumentException exception. 若未偵測到錯誤, 則會忽略不正確序列, 而且不會擲回任何例外狀況。Without error detection, invalid sequences are ignored, and no exception is thrown.

要轉換的資料 (例如從資料流程讀取的資料) 可能只會在連續區塊中提供。Data to be converted, such as data read from a stream, might be available only in sequential blocks. 在此情況下, 或如果資料量太大而需要分割成較小的區塊Decoder , 請分別使用EncoderGetDecoder方法或GetEncoder方法所傳回的或。In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, use the Decoder or the Encoder returned by the GetDecoder method or the GetEncoder method, respectively.

為確保編碼的位元組會在儲存為檔案或資料流程時正確解碼, 您可以在編碼的位元組資料流程前面加上前置字元。To ensure that the encoded bytes are decoded properly when they are saved as a file or as a stream, you can prefix a stream of encoded bytes with a preamble. 將前序插入位元組資料流程的開頭 (例如, 在要寫入檔案的一系列位元組開頭), 是開發人員的責任。Inserting the preamble at the beginning of a byte stream (such as at the beginning of a series of bytes to be written to a file) is the developer's responsibility. GetBytes方法不會在編碼的位元組序列開頭前面加上前導序。The GetBytes method does not prepend a preamble to the beginning of a sequence of encoded bytes.

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

重要

此 API 不符合 CLS 規範。

將起始於指定字元指標的一組字元編碼成位元組序列;儲存該位元組序列時,係以指定的位元組指標為起始點。Encodes a set of characters starting at the specified character pointer into a sequence of bytes that are stored starting at the specified byte pointer.

public:
 override int GetBytes(char* chars, int charCount, System::Byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
[System.Security.SecurityCritical]
public override int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int

參數

chars
Char*

要編碼的第一個字元指標。A pointer to the first character to encode.

charCount
Int32 Int32 Int32 Int32

要編碼的字元數。The number of characters to encode.

bytes
Byte*

開始寫入結果位元組序列的位置指標。A pointer to the location at which to start writing the resulting sequence of bytes.

byteCount
Int32 Int32 Int32 Int32

寫入的最大位元組數。The maximum number of bytes to write.

傳回

bytes 所表示的位置上寫入的實際位元組數目。The actual number of bytes written at the location indicated by bytes.

例外狀況

charsnullchars is null.

-或--or- bytesnullbytes is null.

charCountbyteCount 小於零。charCount or byteCount is less than zero.

已啟用錯誤偵測,而 chars 包含無效的字元序列。Error detection is enabled, and chars contains an invalid sequence of characters.

-或--or- byteCount 小於結果位元組數。byteCount is less than the resulting number of bytes.

備註

若要計算所需GetBytes的確切陣列大小以儲存產生的位元組, 您可以GetByteCount呼叫方法。To calculate the exact array size required by GetBytes to store the resulting bytes, you call the GetByteCount method. 若要計算陣列大小上限, 您可以呼叫GetMaxByteCount方法。To calculate the maximum array size, you call the GetMaxByteCount method. 方法通常會配置較少的GetMaxByteCount記憶體, 而方法通常會更快速地執行。 GetByteCountThe GetByteCount method generally allocates less memory, while the GetMaxByteCount method generally executes faster.

使用錯誤偵測時, 不正確順序會導致這個方法擲ArgumentException回例外狀況。With error detection, an invalid sequence causes this method to throw an ArgumentException exception. 若未偵測到錯誤, 則會忽略不正確序列, 而且不會擲回任何例外狀況。Without error detection, invalid sequences are ignored, and no exception is thrown.

要轉換的資料 (例如從資料流程讀取的資料) 可能只會在連續區塊中提供。Data to be converted, such as data read from a stream, might be available only in sequential blocks. 在此情況下, 或如果資料量太大而需要分割成較小的區塊Decoder , 請分別使用EncoderGetDecoder方法或GetEncoder方法所傳回的或。In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, use the Decoder or the Encoder returned by the GetDecoder method or the GetEncoder method, respectively.

為確保編碼的位元組會在儲存為檔案或資料流程時正確解碼, 您可以在編碼的位元組資料流程前面加上前置字元。To ensure that the encoded bytes are decoded properly when they are saved as a file or as a stream, you can prefix a stream of encoded bytes with a preamble. 將前序插入位元組資料流程的開頭 (例如, 在要寫入檔案的一系列位元組開頭), 是開發人員的責任。Inserting the preamble at the beginning of a byte stream (such as at the beginning of a series of bytes to be written to a file) is the developer's responsibility. GetBytes方法不會在編碼的位元組序列開頭前面加上前導序。The GetBytes method does not prepend a preamble to the beginning of a sequence of encoded bytes.

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。Requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

另請參閱

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

將指定字元陣列中的一組字元編碼成指定的位元組陣列。Encodes a set of characters from the specified character array into the specified byte array.

public:
 override int GetBytes(cli::array <char> ^ chars, int charIndex, int charCount, cli::array <System::Byte> ^ bytes, int byteIndex);
public override int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex);
override this.GetBytes : char[] * int * int * byte[] * int -> int
Public Overrides Function GetBytes (chars As Char(), charIndex As Integer, charCount As Integer, bytes As Byte(), byteIndex As Integer) As Integer

參數

chars
Char[]

包含要解碼之一組字元的字元陣列。The character array containing the set of characters to encode.

charIndex
Int32 Int32 Int32 Int32

要編碼的第一個字元索引。The index of the first character to encode.

charCount
Int32 Int32 Int32 Int32

要編碼的字元數。The number of characters to encode.

bytes
Byte[]

要包含結果位元組序列的位元組陣列。The byte array to contain the resulting sequence of bytes.

byteIndex
Int32 Int32 Int32 Int32

要開始寫入結果位元組序列的索引。The index at which to start writing the resulting sequence of bytes.

傳回

寫入 bytes 的實際位元組數。The actual number of bytes written into bytes.

例外狀況

charsnullchars is null.

-或--or- bytesnullbytes is null.

charIndexcharCountbyteIndex 小於零。charIndex or charCount or byteIndex is less than zero.

-或--or- charIndexcharCount 不代表 chars 中有效的範圍。charIndex and charCount do not denote a valid range in chars.

-或--or- byteIndexbytes 中不是有效的索引。byteIndex is not a valid index in bytes.

已啟用錯誤偵測,而 chars 包含無效的字元序列。Error detection is enabled, and chars contains an invalid sequence of characters.

-或--or- bytes 到陣列結尾處,byteIndex 沒有足夠的容量容納結果位元組。bytes does not have enough capacity from byteIndex to the end of the array to accommodate the resulting bytes.

範例

下列範例會使用GetBytes方法, 將字串中的字元範圍編碼, 並將編碼的位元組儲存在位元組陣列中的某個範圍內。The following example uses the GetBytes method to encode a range of characters from a string and stores the encoded bytes in a range of elements in a byte array.

using namespace System;
using namespace System::Text;
using namespace System::Collections;
int main()
{
   array<Byte>^bytes;
   String^ chars = "UTF8 Encoding Example";
   UTF8Encoding^ utf8 = gcnew UTF8Encoding;
   int byteCount = utf8->GetByteCount( chars->ToCharArray(), 0, 13 );
   bytes = gcnew array<Byte>(byteCount);
   int bytesEncodedCount = utf8->GetBytes( chars, 0, 13, bytes, 0 );
   Console::WriteLine( "{0} bytes used to encode string.", bytesEncodedCount );
   Console::Write( "Encoded bytes: " );
   IEnumerator^ myEnum = bytes->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Byte b = safe_cast<Byte>(myEnum->Current);
      Console::Write( "[{0}]", b );
   }

   Console::WriteLine();
}

using System;
using System.Text;

class UTF8EncodingExample {
    public static void Main() {
        Byte[] bytes;
        String chars = "UTF8 Encoding Example";
        
        UTF8Encoding utf8 = new UTF8Encoding();
        
        int byteCount = utf8.GetByteCount(chars.ToCharArray(), 0, 13);
        bytes = new Byte[byteCount];
        int bytesEncodedCount = utf8.GetBytes(chars, 0, 13, bytes, 0);
        
        Console.WriteLine(
            "{0} bytes used to encode string.", bytesEncodedCount
        );

        Console.Write("Encoded bytes: ");
        foreach (Byte b in bytes) {
            Console.Write("[{0}]", b);
        }
        Console.WriteLine();
    }
}
Imports System.Text

Class UTF8EncodingExample
    
    Public Shared Sub Main()
        Dim bytes() As Byte
        Dim chars As String = "UTF8 Encoding Example"
        
        Dim utf8 As New UTF8Encoding()
        
        Dim byteCount As Integer = utf8.GetByteCount(chars.ToCharArray(), 0, 13)
        bytes = New Byte(byteCount - 1) {}
        Dim bytesEncodedCount As Integer = utf8.GetBytes(chars, 0, 13, bytes, 0)
        
        Console.WriteLine("{0} bytes used to encode string.", bytesEncodedCount)
        
        Console.Write("Encoded bytes: ")
        Dim b As Byte
        For Each b In  bytes
            Console.Write("[{0}]", b)
        Next b
        Console.WriteLine()
    End Sub
End Class

備註

若要計算所需GetBytes的確切陣列大小以儲存產生的位元組, 您可以GetByteCount呼叫方法。To calculate the exact array size required by GetBytes to store the resulting bytes, you call the GetByteCount method. 若要計算陣列大小上限, 您可以呼叫GetMaxByteCount方法。To calculate the maximum array size, you call the GetMaxByteCount method. 方法通常會配置較少的GetMaxByteCount記憶體, 而方法通常會更快速地執行。 GetByteCountThe GetByteCount method generally allocates less memory, while the GetMaxByteCount method generally executes faster.

使用錯誤偵測時, 不正確順序會導致這個方法擲ArgumentException回例外狀況。With error detection, an invalid sequence causes this method to throw an ArgumentException exception. 若未偵測到錯誤, 則會忽略不正確序列, 而且不會擲回任何例外狀況。Without error detection, invalid sequences are ignored, and no exception is thrown.

要轉換的資料 (例如從資料流程讀取的資料) 可能只會在連續區塊中提供。Data to be converted, such as data read from a stream, might be available only in sequential blocks. 在此情況下, 或如果資料量太大而需要分割成較小的區塊Decoder , 請分別使用EncoderGetDecoder方法GetEncoder所提供的或。In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively.

為確保編碼的位元組會在儲存為檔案或資料流程時正確解碼, 您可以在編碼的位元組資料流程前面加上前置字元。To ensure that the encoded bytes are decoded properly when they are saved as a file or as a stream, you can prefix a stream of encoded bytes with a preamble. 將前序插入位元組資料流程的開頭 (例如, 在要寫入檔案的一系列位元組開頭), 是開發人員的責任。Inserting the preamble at the beginning of a byte stream (such as at the beginning of a series of bytes to be written to a file) is the developer's responsibility. GetBytes方法不會在編碼的位元組序列開頭前面加上前導序。The GetBytes method does not prepend a preamble to the beginning of a sequence of encoded bytes.

另請參閱

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

將指定 String 中的一組字元編碼成指定的位元組陣列。Encodes a set of characters from the specified String into the specified byte array.

public:
 override int GetBytes(System::String ^ s, int charIndex, int charCount, cli::array <System::Byte> ^ bytes, int byteIndex);
public override int GetBytes (string s, int charIndex, int charCount, byte[] bytes, int byteIndex);
override this.GetBytes : string * int * int * byte[] * int -> int
Public Overrides Function GetBytes (s As String, charIndex As Integer, charCount As Integer, bytes As Byte(), byteIndex As Integer) As Integer

參數

s
String String String String

String,包含要編碼的一組字元。The String containing the set of characters to encode.

charIndex
Int32 Int32 Int32 Int32

要編碼的第一個字元索引。The index of the first character to encode.

charCount
Int32 Int32 Int32 Int32

要編碼的字元數。The number of characters to encode.

bytes
Byte[]

要包含結果位元組序列的位元組陣列。The byte array to contain the resulting sequence of bytes.

byteIndex
Int32 Int32 Int32 Int32

要開始寫入結果位元組序列的索引。The index at which to start writing the resulting sequence of bytes.

傳回

寫入 bytes 的實際位元組數。The actual number of bytes written into bytes.

例外狀況

snulls is null.

-或--or- bytesnullbytes is null.

charIndexcharCountbyteIndex 小於零。charIndex or charCount or byteIndex is less than zero.

-或--or- charIndexcharCount 不代表 chars 中有效的範圍。charIndex and charCount do not denote a valid range in chars.

-或--or- byteIndexbytes 中不是有效的索引。byteIndex is not a valid index in bytes.

已啟用錯誤偵測,而 s 包含無效的字元序列。Error detection is enabled, and s contains an invalid sequence of characters.

-或--or- bytes 到陣列結尾處,byteIndex 沒有足夠的容量容納結果位元組。bytes does not have enough capacity from byteIndex to the end of the array to accommodate the resulting bytes.

範例

下列範例使用GetBytes方法來編碼來自 Unicode 字元陣列的某個範圍的專案, 並將編碼的位元組儲存在位元組陣列中的某個範圍內。The following example uses the GetBytes method to encode a range of elements from a Unicode character array and store the encoded bytes in a range of elements in a byte array.

using namespace System;
using namespace System::Text;
using namespace System::Collections;
int main()
{
   array<Byte>^bytes;
   
   // Unicode characters.
   
   // Pi
   // Sigma
   array<Char>^chars = {L'\u03a0',L'\u03a3',L'\u03a6',L'\u03a9'};
   UTF8Encoding^ utf8 = gcnew UTF8Encoding;
   int byteCount = utf8->GetByteCount( chars, 1, 2 );
   bytes = gcnew array<Byte>(byteCount);
   int bytesEncodedCount = utf8->GetBytes( chars, 1, 2, bytes, 0 );
   Console::WriteLine( "{0} bytes used to encode characters.", bytesEncodedCount );
   Console::Write( "Encoded bytes: " );
   IEnumerator^ myEnum = bytes->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Byte b = safe_cast<Byte>(myEnum->Current);
      Console::Write( "[{0}]", b );
   }

   Console::WriteLine();
}

using System;
using System.Text;

class UTF8EncodingExample {
    public static void Main() {
        Byte[] bytes;
        // Unicode characters.
        Char[] chars = new Char[] {
            '\u0023', // #
            '\u0025', // %
            '\u03a0', // Pi
            '\u03a3'  // Sigma
        };
        
        UTF8Encoding utf8 = new UTF8Encoding();
        
        int byteCount = utf8.GetByteCount(chars, 1, 2);
        bytes = new Byte[byteCount];
        int bytesEncodedCount = utf8.GetBytes(chars, 1, 2, bytes, 0);
        
        Console.WriteLine(
            "{0} bytes used to encode characters.", bytesEncodedCount
        );

        Console.Write("Encoded bytes: ");
        foreach (Byte b in bytes) {
            Console.Write("[{0}]", b);
        }
        Console.WriteLine();
    }
}
Imports System.Text
Imports Microsoft.VisualBasic.Strings

Class UTF8EncodingExample
    
    Public Shared Sub Main()
        Dim bytes() As Byte
        ' Unicode characters.
        ' ChrW(35)  = #
        ' ChrW(37)  = %
        ' ChrW(928) = Pi
        ' ChrW(931) = Sigma
        Dim chars() As Char = {ChrW(35), ChrW(37), ChrW(928), ChrW(931)}
        
        Dim utf8 As New UTF8Encoding()
        
        Dim byteCount As Integer = utf8.GetByteCount(chars, 1, 2)
        bytes = New Byte(byteCount - 1) {}
        Dim bytesEncodedCount As Integer = utf8.GetBytes(chars, 1, 2, bytes, 0)
        
        Console.WriteLine("{0} bytes used to encode characters.", bytesEncodedCount)
        
        Console.Write("Encoded bytes: ")
        Dim b As Byte
        For Each b In  bytes
            Console.Write("[{0}]", b)
        Next b
        Console.WriteLine()
    End Sub
End Class

備註

若要計算所需GetBytes的確切陣列大小以儲存產生的位元組, 您可以GetByteCount呼叫方法。To calculate the exact array size required by GetBytes to store the resulting bytes, you call the GetByteCount method. 若要計算陣列大小上限, 您可以呼叫GetMaxByteCount方法。To calculate the maximum array size, you call the GetMaxByteCount method. 方法通常會配置較少的GetMaxByteCount記憶體, 而方法通常會更快速地執行。 GetByteCountThe GetByteCount method generally allocates less memory, while the GetMaxByteCount method generally executes faster.

使用錯誤偵測時, 不正確順序會導致這個方法擲ArgumentException回例外狀況。With error detection, an invalid sequence causes this method to throw an ArgumentException exception. 若未偵測到錯誤, 則會忽略不正確序列, 而且不會擲回任何例外狀況。Without error detection, invalid sequences are ignored, and no exception is thrown.

要轉換的資料 (例如從資料流程讀取的資料) 可能只會在連續區塊中提供。Data to be converted, such as data read from a stream, might be available only in sequential blocks. 在此情況下, 或如果資料量太大而需要分割成較小的區塊Decoder , 請分別使用EncoderGetDecoder方法GetEncoder所提供的或。In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively.

為確保編碼的位元組會在儲存為檔案或資料流程時正確解碼, 您可以在編碼的位元組資料流程前面加上前置字元。To ensure that the encoded bytes are decoded properly when they are saved as a file or as a stream, you can prefix a stream of encoded bytes with a preamble. 將前序插入位元組資料流程的開頭 (例如, 在要寫入檔案的一系列位元組開頭), 是開發人員的責任。Inserting the preamble at the beginning of a byte stream (such as at the beginning of a series of bytes to be written to a file) is the developer's responsibility. GetBytes方法不會在編碼的位元組序列開頭前面加上前導序。The GetBytes method does not prepend a preamble to the beginning of a sequence of encoded bytes.

另請參閱

適用於