Using .NET’s SerialPort Class
For example, a 5-byte string has a 1-byte prefix of 05h. A 128-byte string has a
2-byte prefix of 80h 01h. The length to be encoded (128) equals 10000000b.
The length value has 8 bits so the prefix is 2 bytes. In the prefix’s first byte
(80h), bits 0–6 match bits 0–6 in the length value and bit 7 = 1 to indicate
there is another prefix byte. In the prefix’s second byte (01h), bit 0 matches bit
7 in the length value, bits 1–6 are zeroes, and bit 7 equals zero to indicate that
the current byte is the last byte in the prefix.
The value being encoded is the number of bytes transmitted, not the number of
characters, and excludes the prefix. When a BinaryWriter sends a © character
by writing the bytes C2h A9h, the prefix is 2 to indicate 2 bytes being transmit-
ted.
To write a String with BinaryWriter, use the Write method:
Dim valueToWrite As String
valueToWrite = "hello"
binaryWriter1.Write(valueToWrite)
String valueToWrite ;
valueToWrite = "hello";
binaryWriter1.Write( valueToWrite );
To read a String with BinaryReader, use the ReadString method:
Dim receivedData As String
receivedData = binaryReader1.ReadString
Console.WriteLine(receivedData)
String receivedData;
receivedData = binaryReader1.ReadString();
Console.WriteLine(receivedData):
The ReadString method uses the length prefix to determine the string’s length,
discards the prefix, and returns the string that follows. If transmitted data
doesn’t include a length prefix, the receiving computer interprets the initial
byte(s) as a length value instead of text data and thus doesn’t read the correct
string and raises a TimeoutException if the expected number of bytes doesn’t
arrive.