UnicodeEncoding.GetBytes Método
Definição
Codifica um conjunto de caracteres em uma sequência de bytes.Encodes a set of characters into a sequence of bytes.
Sobrecargas
| GetBytes(Char[], Int32, Int32, Byte[], Int32) |
Codifica um conjunto de caracteres da matriz de caracteres especificada na matriz de bytes especificada.Encodes a set of characters from the specified character array into the specified byte array. |
| GetBytes(String, Int32, Int32, Byte[], Int32) |
Codifica um conjunto de caracteres do String especificado para a matriz de bytes especificada.Encodes a set of characters from the specified String into the specified byte array. |
| GetBytes(String) |
Codifica um conjunto de caracteres da cadeia de caracteres indicada para a matriz de bytes especificada.Encodes a set of characters from the specified string into the specified byte array. |
| GetBytes(Char*, Int32, Byte*, Int32) |
Codifica um conjunto de caracteres começando no ponteiro de caractere especificado em uma sequência de bytes armazenados começando no ponteiro de byte especificado.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)
Codifica um conjunto de caracteres da matriz de caracteres especificada na matriz de bytes especificada.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
Parâmetros
- chars
- Char[]
A matriz de caracteres que contém o conjunto de caracteres a serem codificados.The character array containing the set of characters to encode.
- charIndex
- Int32
O índice do primeiro caractere a ser codificado.The index of the first character to encode.
- charCount
- Int32
O número de caracteres a ser codificado.The number of characters to encode.
- bytes
- Byte[]
A matriz de bytes que conterá a sequência de bytes resultante.The byte array to contain the resulting sequence of bytes.
- byteIndex
- Int32
O índice no qual será iniciada a gravação da sequência de bytes resultante.The index at which to start writing the resulting sequence of bytes.
Retornos
O número real de bytes gravados no bytes.The actual number of bytes written into bytes.
Exceções
chars é null (Nothing).chars is null (Nothing).
- ou --or-
bytes é null (Nothing).bytes is null (Nothing).
charIndex, charCount ou byteIndex é menor que zero.charIndex or charCount or byteIndex is less than zero.
- ou --or-
charIndex e charCount não denotam um intervalo válido em chars.charIndex and charCount do not denote a valid range in chars.
- ou --or-
byteIndex não é um índice válido em bytes.byteIndex is not a valid index in bytes.
A detecção de erros está habilitada e chars contém uma sequência de caracteres inválida.Error detection is enabled, and chars contains an invalid sequence of characters.
- ou --or-
O bytes não tem capacidade suficiente do byteIndex ao final da matriz para acomodar os bytes resultantes.bytes does not have enough capacity from byteIndex to the end of the array to accommodate the resulting bytes.
Ocorreu um fallback (saiba mais em Codificação de caracteres no .NET)A fallback occurred (for more information, see Character Encoding in .NET) -e--and- EncoderFallback é definido como EncoderExceptionFallback.EncoderFallback is set to EncoderExceptionFallback.
Exemplos
O exemplo a seguir demonstra como usar o GetBytes método para codificar um intervalo de caracteres de a String e armazenar os bytes codificados em um intervalo de elementos em uma matriz de bytes.The following example demonstrates how to use the GetBytes method to encode a range of characters from a String 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;
String^ chars = "Unicode Encoding Example";
UnicodeEncoding^ Unicode = gcnew UnicodeEncoding;
int byteCount = Unicode->GetByteCount( chars->ToCharArray(), 8, 8 );
bytes = gcnew array<Byte>(byteCount);
int bytesEncodedCount = Unicode->GetBytes( chars, 8, 8, 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 UnicodeEncodingExample {
public static void Main() {
Byte[] bytes;
String chars = "Unicode Encoding Example";
UnicodeEncoding Unicode = new UnicodeEncoding();
int byteCount = Unicode.GetByteCount(chars.ToCharArray(), 8, 8);
bytes = new Byte[byteCount];
int bytesEncodedCount = Unicode.GetBytes(chars, 8, 8, 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 UnicodeEncodingExample
Public Shared Sub Main()
Dim bytes() As Byte
Dim chars As String = "Unicode Encoding Example"
Dim uni As New UnicodeEncoding()
Dim byteCount As Integer = uni.GetByteCount(chars.ToCharArray(), 8, 8)
bytes = New Byte(byteCount - 1) {}
Dim bytesEncodedCount As Integer = uni.GetBytes(chars, 8, 8, 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
Comentários
Para calcular o tamanho exato da matriz exigido pelo GetBytes para armazenar os bytes resultantes, chame o GetByteCount método.To calculate the exact array size required by GetBytes to store the resulting bytes, you call the GetByteCount method. Para calcular o tamanho máximo da matriz, chame o GetMaxByteCount método.To calculate the maximum array size, you call the GetMaxByteCount method. O GetByteCount método geralmente aloca menos memória, enquanto o GetMaxByteCount método geralmente é executado mais rapidamente.The GetByteCount method generally allocates less memory, while the GetMaxByteCount method generally executes faster.
Com a detecção de erro, uma sequência inválida faz com que esse método gere um ArgumentException .With error detection, an invalid sequence causes this method to throw a ArgumentException. Sem a detecção de erros, as sequências inválidas são ignoradas e nenhuma exceção é lançada.Without error detection, invalid sequences are ignored, and no exception is thrown.
Os dados a serem convertidos, como dados lidos de um fluxo, podem estar disponíveis somente em blocos sequenciais.Data to be converted, such as data read from a stream, might be available only in sequential blocks. Nesse caso, ou se a quantidade de dados for tão grande que precisa ser dividida em blocos menores, o aplicativo deverá usar o Decoder ou o Encoder fornecido pelo GetDecoder método ou pelo GetEncoder método, respectivamente.In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively.
Importante
Para garantir que os bytes codificados sejam decodificados corretamente quando eles são salvos como um arquivo ou como um fluxo, você pode prefixar um fluxo de bytes codificados com um preâmbulo.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. A inserção do preâmbulo no início de um fluxo de bytes (como no início de uma série de bytes a ser gravado em um arquivo) é a responsabilidade do desenvolvedor.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. O GetBytes método não precede um preâmbulo para o início de uma sequência de bytes codificados.The GetBytes method does not prepend a preamble to the beginning of a sequence of encoded bytes.
Confira também
Aplica-se a
GetBytes(String, Int32, Int32, Byte[], Int32)
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
Parâmetros
- s
- String
A cadeia de caracteres que contém o conjunto de caracteres a ser codificado.The string containing the set of characters to encode.
- charIndex
- Int32
O índice do primeiro caractere a ser codificado.The index of the first character to encode.
- charCount
- Int32
O número de caracteres a ser codificado.The number of characters to encode.
- bytes
- Byte[]
A matriz de bytes que conterá a sequência de bytes resultante.The byte array to contain the resulting sequence of bytes.
- byteIndex
- Int32
O índice no qual será iniciada a gravação da sequência de bytes resultante.The index at which to start writing the resulting sequence of bytes.
Retornos
O número real de bytes gravados no bytes.The actual number of bytes written into bytes.
Exceções
s é null.s is null.
- ou --or-
bytes é null (Nothing).bytes is null (Nothing).
charIndex, charCount ou byteIndex é menor que zero.charIndex or charCount or byteIndex is less than zero.
- ou --or-
charIndex e charCount não denotam um intervalo válido em chars.charIndex and charCount do not denote a valid range in chars.
- ou --or-
byteIndex não é um índice válido em bytes.byteIndex is not a valid index in bytes.
A detecção de erros está habilitada e s contém uma sequência de caracteres inválida.Error detection is enabled, and s contains an invalid sequence of characters.
- ou --or-
O bytes não tem capacidade suficiente do byteIndex ao final da matriz para acomodar os bytes resultantes.bytes does not have enough capacity from byteIndex to the end of the array to accommodate the resulting bytes.
Ocorreu um fallback (saiba mais em Codificação de caracteres no .NET)A fallback occurred (for more information, see Character Encoding in .NET) -e--and- EncoderFallback é definido como EncoderExceptionFallback.EncoderFallback is set to EncoderExceptionFallback.
Exemplos
O exemplo a seguir demonstra como codificar um intervalo de elementos de uma matriz de caracteres Unicode e armazenar os bytes codificados em um intervalo de elementos em uma matriz de bytes.The following example demonstrates how 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'};
UnicodeEncoding^ Unicode = gcnew UnicodeEncoding;
int byteCount = Unicode->GetByteCount( chars, 1, 2 );
bytes = gcnew array<Byte>(byteCount);
int bytesEncodedCount = Unicode->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 UnicodeEncodingExample {
public static void Main() {
Byte[] bytes;
// Unicode characters.
Char[] chars = new Char[] {
'\u0023', // #
'\u0025', // %
'\u03a0', // Pi
'\u03a3' // Sigma
};
UnicodeEncoding Unicode = new UnicodeEncoding();
int byteCount = Unicode.GetByteCount(chars, 1, 2);
bytes = new Byte[byteCount];
int bytesEncodedCount = Unicode.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 UnicodeEncodingExample
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 uni As New UnicodeEncoding()
Dim byteCount As Integer = uni.GetByteCount(chars, 1, 2)
bytes = New Byte(byteCount - 1) {}
Dim bytesEncodedCount As Integer = uni.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
Comentários
Para calcular o tamanho exato da matriz exigido pelo GetBytes para armazenar os bytes resultantes, chame o GetByteCount método.To calculate the exact array size required by GetBytes to store the resulting bytes, you call the GetByteCount method. Para calcular o tamanho máximo da matriz, chame o GetMaxByteCount método.To calculate the maximum array size, you call the GetMaxByteCount method. O GetByteCount método geralmente aloca menos memória, enquanto o GetMaxByteCount método geralmente é executado mais rapidamente.The GetByteCount method generally allocates less memory, while the GetMaxByteCount method generally executes faster.
Com a detecção de erro, uma sequência inválida faz com que esse método gere um ArgumentException .With error detection, an invalid sequence causes this method to throw a ArgumentException. Sem a detecção de erros, as sequências inválidas são ignoradas e nenhuma exceção é lançada.Without error detection, invalid sequences are ignored, and no exception is thrown.
Os dados a serem convertidos, como dados lidos de um fluxo, podem estar disponíveis somente em blocos sequenciais.Data to be converted, such as data read from a stream, might be available only in sequential blocks. Nesse caso, ou se a quantidade de dados for tão grande que precisa ser dividida em blocos menores, o aplicativo deverá usar o Decoder ou o Encoder fornecido pelo GetDecoder método ou pelo GetEncoder método, respectivamente.In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively.
Importante
Para garantir que os bytes codificados sejam decodificados corretamente quando eles são salvos como um arquivo ou como um fluxo, você pode prefixar um fluxo de bytes codificados com um preâmbulo.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. A inserção do preâmbulo no início de um fluxo de bytes (como no início de uma série de bytes a ser gravado em um arquivo) é a responsabilidade do desenvolvedor.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. O GetBytes método não precede um preâmbulo para o início de uma sequência de bytes codificados.The GetBytes method does not prepend a preamble to the beginning of a sequence of encoded bytes.
Confira também
Aplica-se a
GetBytes(String)
Codifica um conjunto de caracteres da cadeia de caracteres indicada para a matriz de bytes especificada.Encodes a set of characters from the specified string into the specified byte array.
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()
Parâmetros
- s
- String
Retornos
- Byte[]
Aplica-se a
GetBytes(Char*, Int32, Byte*, Int32)
Importante
Esta API não está em conformidade com CLS.
Codifica um conjunto de caracteres começando no ponteiro de caractere especificado em uma sequência de bytes armazenados começando no ponteiro de byte especificado.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)]
public override int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
public override int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public override int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetBytes (char* chars, int charCount, byte* bytes, int byteCount);
[<System.CLSCompliant(false)>]
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
[<System.CLSCompliant(false)>]
[<System.Runtime.InteropServices.ComVisible(false)>]
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(false)>]
override this.GetBytes : nativeptr<char> * int * nativeptr<byte> * int -> int
Parâmetros
- chars
- Char*
Um ponteiro para o primeiro caractere a ser codificado.A pointer to the first character to encode.
- charCount
- Int32
O número de caracteres a ser codificado.The number of characters to encode.
- bytes
- Byte*
Um ponteiro para o local no qual a gravação da sequência de bytes resultante deve ser iniciada.A pointer to the location at which to start writing the resulting sequence of bytes.
- byteCount
- Int32
O número máximo de bytes a serem gravados.The maximum number of bytes to write.
Retornos
O número real de bytes gravados no local indicado pelo parâmetro bytes.The actual number of bytes written at the location indicated by the bytes parameter.
- Atributos
Exceções
chars é null (Nothing).chars is null (Nothing).
- ou --or-
bytes é null (Nothing).bytes is null (Nothing).
charCount ou byteCount é menor que zero.charCount or byteCount is less than zero.
A detecção de erros está habilitada e chars contém uma sequência de caracteres inválida.Error detection is enabled, and chars contains an invalid sequence of characters.
- ou --or-
byteCount é menor que o número de bytes resultante.byteCount is less than the resulting number of bytes.
Ocorreu um fallback (saiba mais em Codificação de caracteres no .NET)A fallback occurred (for more information, see Character Encoding in .NET) -e--and- EncoderFallback é definido como EncoderExceptionFallback.EncoderFallback is set to EncoderExceptionFallback.
Comentários
Para calcular o tamanho exato da matriz que GetBytes o exige para armazenar os bytes resultantes, chame o GetByteCount método.To calculate the exact array size that GetBytes requires to store the resulting bytes, you call the GetByteCount method. Para calcular o tamanho máximo da matriz, chame o GetMaxByteCount método.To calculate the maximum array size, you call the GetMaxByteCount method. O GetByteCount método geralmente aloca menos memória, enquanto o GetMaxByteCount método geralmente é executado mais rapidamente.The GetByteCount method generally allocates less memory, while the GetMaxByteCount method generally executes faster.
Com a detecção de erro, uma sequência inválida faz com que esse método gere um ArgumentException .With error detection, an invalid sequence causes this method to throw a ArgumentException. Sem a detecção de erros, as sequências inválidas são ignoradas e nenhuma exceção é lançada.Without error detection, invalid sequences are ignored, and no exception is thrown.
Os dados a serem convertidos, como dados lidos de um fluxo, podem estar disponíveis somente em blocos sequenciais.Data to be converted, such as data read from a stream, might be available only in sequential blocks. Nesse caso, ou se a quantidade de dados for tão grande que precisa ser dividida em blocos menores, o aplicativo deverá usar o Decoder ou o Encoder objeto fornecido pelo GetDecoder ou o GetEncoder método, respectivamente.In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder object provided by the GetDecoder or the GetEncoder method, respectively.
Importante
Para garantir que os bytes codificados sejam decodificados corretamente quando eles são salvos como um arquivo ou como um fluxo, você pode prefixar um fluxo de bytes codificados com um preâmbulo.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. A inserção do preâmbulo no início de um fluxo de bytes (como no início de uma série de bytes a ser gravado em um arquivo) é a responsabilidade do desenvolvedor.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. O GetBytes método não precede um preâmbulo para o início de uma sequência de bytes codificados.The GetBytes method does not prepend a preamble to the beginning of a sequence of encoded bytes.