UTF8Encoding: GetBytesEx |
Encodes a set of characters into an array of bytes, returning the number of bytes produced.
Public Function GetBytesEx( ByRef Chars As Variant, ByVal CharIndex As Long, ByVal CharCount As Long, ByRef Bytes ( ) As Byte, ByVal ByteIndex As Long ) As Long
To calculate the exact array size required by GetBytesEx to store the resulting bytes, the application uses GetByteCount. To calculate the maximum array size, the application should use GetMaxByteCount. The GetByteCount method generally allows allocation of less memory, while the GetMaxByteCount method generally executes faster.
With error detection, an invalid sequence causes this method to throw a ArgumentException. 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. In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, the application uses the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively.
Note |
---|
To ensure that the encoded bytes are decoded properly, the application should prefix encoded bytes with a preamble. |
Exception | Condition |
---|---|
ArgumentNullException | Chars is an unintialized array. -or- Byte is an uninitialized array. |
ArgumentOutOfRangeException | CharIndex is less than the lower-bound of Chars. -or- ByteIndex is less than the lower-bound of Bytes. -or- CharCount is less than zero. -or- CharIndex and CharCount do not denote a valid range in Chars. -or- ByteIndex is not a valid index in Bytes. |
ArgumentException | Error detection is enabled, and Chars contains an invalid sequence of characters. -or- Bytes does not have enough capacity from ByteIndex to the end of the array to accommodate the resulting bytes. |
EncoderFallbackException | A fallback occurred -and- EncoderFallback is set to EncoderExceptionFallback. |
The following example demonstrates how to use the GetBytesEx method to encode a range of characters from a String and store the encoded bytes in a range of elements in a byte array.
Public Sub Main() Dim Bytes() As Byte Dim Chars As String Dim ByteCount As Long Dim BytesEncodedCount As Long Dim UTF8 As New UTF8Encoding Dim b As Variant Chars = "UTF8 Encoding Example" ByteCount = UTF8.GetByteCount(CorString.ToCharArray(Chars), 0, 13) ReDim Bytes(1 To ByteCount) BytesEncodedCount = UTF8.GetBytesEx(Chars, 0, 13, Bytes, 1) Console.WriteLine "{0} bytes used to encode string.", BytesEncodedCount Console.WriteValue "Encoded bytes: " For Each b In Bytes Console.WriteValue "[{0}]", b Next Console.WriteLine Console.ReadKey End Sub ' This code produces the following output. ' ' 13 bytes used to encode string. ' Encoded bytes: [85][84][70][56][32][69][110][99][111][100][105][110][103]