BinaryReader: ReadString

ReadString

Reads a String from the stream.

 Public Function ReadString ( ) As String

Return Values

String -  The string datatype.

Remarks

The string is stored in the stream with the number of encoded bytes preceding the actual string data. The bytes are not the typical 4 bytes as is used by VB when representing the length of the string. The bytes represent a value encoded as 7bits per byte. While the next read byte has the high bit set (&H80), then the following byte is also part of the length value. For each byte read, first 7 bits of that byte is pushed out 7 bits multiplied by the current byte number - 1 in the sequence. This is not the normal shifting of the current sum of the values. Each read byte must be shifted left individually, as each byte represents a higher set of bits in the resulting number.

We AND the byte with &H3f because we only want the lower 7 bits.
byte 1: (byte and &H3f) << shifted 0 bits added to the sum
byte 2: (byte and &H3f) << shifted 7 bits added to the sum
byte 3: (byte and &H3f) << shifted 14 bits added to the sum

.. this continues until a byte is less than 128. At which point, it is shifted and summed like the rest, but no more bytes are to be read in. The sum now contains the number of bytes to be read in and decoded into the string. The same Encoding type must be used to retrieve the correct string value. Using a different Encoding method will create the wrong string.

Once the length is determined, then enough bytes are read in that can be decoded to the string using the current Encoding system.

See Also

Project VBCorLib Overview | Class BinaryReader Overview