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:


using System;
using System.IO;
namespace BitConverterExample
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Int32 Max value: " +System.Int32.MaxValue.ToString());
int test = Int32.MaxValue ;
byte[] bytInt=new byte[4];
bytInt= Int32ToBytes(test);
int test2 = BytesToInt32(bytInt);
Console.WriteLine("Result is: " +test2.ToString());
MemoryStream stm = new MemoryStream();
string message="This is a sample message to test out.";
byte[] msgBytes=System.Text.Encoding.UTF8.GetBytes(message);
byte[] finalMsg=EncodeMessageWithHeader(msgBytes);
stm.Write(finalMsg,0,finalMsg.Length );
stm.Position =0;
byte[] resultBytes=DecodeMessageWithHeader(stm);
string finalResult=System.Text.Encoding.UTF8.GetString(resultBytes);
Console.WriteLine("Result: " +finalResult);
Console.ReadLine();
}

private static Int32 BytesToInt32(byte[] FourByteArrToConvert)
{
return System.BitConverter.ToInt32(FourByteArrToConvert,0);
}
private static byte[] Int32ToBytes(Int32 int32Input)
{
byte[] numBytesBuf = new byte[4];
return System.BitConverter.GetBytes(int32Input);
}

private static byte[] DecodeMessageWithHeader(MemoryStream ms)
{
byte[] numBytesToRead= new byte[4];
ms.Read(numBytesToRead,0,4);
Int32 intBytesToRead=BytesToInt32(numBytesToRead);
byte[] msgBytes=new byte[intBytesToRead];
ms.Read(msgBytes,0,intBytesToRead);
return msgBytes;
}
private static byte[] EncodeMessageWithHeader( byte[] msg)
{
int len = msg.Length;
byte[] numBytes=Int32ToBytes(len);
MemoryStream ms= new MemoryStream();
ms.Write(numBytes,0,4);
ms.Write(msg,0,msg.Length);
ms.Position =0;
return ms.ToArray();
}
}
}

Comments

Popular posts from this blog

Some observations on Script Callbacks, "AJAX", "ATLAS" "AHAB" and where it's all going.

IE7 - Vista: "Internet Explorer has stopped Working"

FIREFOX / IE Word-Wrap, Word-Break, TABLES FIX