Click or drag to resize

BinaryTextEncodingFixedLength Method

Returns an encoder that will encode and decode fixed length string given a character encoding.

Namespace: Demo3D.IO
Assembly: Demo3D.IO (in Demo3D.IO.dll) Version: 19.01.00
Syntax
C#
public static BinaryTextEncoding FixedLength(
	Encoding characterEncoding,
	ushort length = 0
)

Parameters

characterEncoding  Encoding
The character encoding.
length  UInt16  (Optional)
The fixed length of the string in bytes (or 0).

Return Value

BinaryTextEncoding
An instance of BinaryTextEncoding that will encode and decode strings in this format.
Remarks
If length is 0 then the length of the string is determined dynamically. When reading a string, all the data in the IDataReader will be consumed and converted to a string. When writing a string, all the characters in the string are written to the IDataWriter.
Example

The following example shows simple examples for reading and writing fixed/variable length strings.

C#
// These first two examples show how to read/write variable-length strings to/from a packet.
public void VariableLengthStrings(IDataReader receivedPacket, IDataWriter packetToSend) {
    // Reads all the bytes in 'receivedPacket' and converts it all into an ASCII string.
    var str = receivedPacket.ReadString(BinaryTextEncoding.FixedLengthASCII);

    // Writes the string "hello" into a packet ready to be sent to the peer.
    packetToSend.WriteString("hello", BinaryTextEncoding.FixedLengthASCII);
}

// Sometimes there's more data in a packet than just one string.  In which case, it may be
// necessary to specify exactly how long the string is that we're expecting to read.
public void FixedLengthStrings(IDataReader receivedPacket, ushort lengthOfString) {
    // Reads 'lengthOfString' bytes of data from 'receivedPacket' and then interprets them as Unicode (UTF-16).
    var str = receivedPacket.ReadString(BinaryTextEncoding.FixedLength(System.Text.Encoding.Unicode, lengthOfString));
}
See Also