Вот так например (только в качестве идеи).
// Это небольшой хелпер
public sealed class Pack
{
readonly MemoryStream inner = new MemoryStream( );
public Pack Byte( byte value )
{
this.inner.WriteByte(value);
return this;
}
public Pack Int32( Int32 value )
{
//Меняем порядок байт
this.inner.WriteByte( unchecked( (byte)( value >> 24 & 0xff ) ) );
this.inner.WriteByte( unchecked( (byte)( value >> 16 & 0xff ) ) );
this.inner.WriteByte( unchecked( (byte)( value >> 8 & 0xff ) ) );
this.inner.WriteByte( unchecked( (byte)( value & 0xff ) ) );
return this;
}
public Pack Empty( int size )
{
byte[] zero = new byte[size];
this.inner.Write(zero, 0, zero.Length);
return this;
}
public byte[] GetData()
{
return this.inner.ToArray();
}
}
// А используем так:
Pack pk = new Pack()
.Int32(len)
.Int32(seconds)
.Int32(msgId)
.Empty(32)
.Int32(clientId)
.Byte(flags1)
.Byte(flags2)
.Int32(keyId)
.Empty(48);
byte[] toWrite = pk.GetData();
networkStream.Write(toWrite, 0, toWrite.Length);