BitConverter for encoding integer values to bytes and reverse
Often when working with streams, in particular when the stream does not support seek operations, we need to be able to transmit the number of bytes in the message as a "header" at the beginning of the message.
In this manner, all we need to do is read the first four bytes out of the stream, convert to an integer value, and then it's a snap to read out exactly the correct number of subsequent bytes to get our entire message.
Here is a sample class using the methods in the System.BitConverter class, along with a sample MemoryStream and string message, to illustrate how this can be done:
In this manner, all we need to do is read the first four bytes out of the stream, convert to an integer value, and then it's a snap to read out exactly the correct number of subsequent bytes to get our entire message.
Here is a sample class using the methods in the System.BitConverter class, along with a sample MemoryStream and string message, to illustrate how this can be done:
using System; |
Comments
Post a Comment