Getting things into an array of bytes

  • Thread starter Thread starter Sijmen Mulder
  • Start date Start date
S

Sijmen Mulder

Hi there,

Currently I'm trying to think of a way to quickly send data back and
forth for a game, over sockets.

I thought the best way would be to have a struct like this:

struct NetMessage
{
public NetMessageType Type;
public byte[] Contents;
}

However, now I'm wondering how to send the data as bytes. I've often
used the BinaryWriter, but can I get the resulting bytes as an array
from it?

In other words, how can I take some base objects, such as strings and
ints, and turn them into an array of bytes without using the
BinaryFormatter?

Thanks,
Sijmen Mulder
 
Sijmen Mulder said:
Currently I'm trying to think of a way to quickly send data back and
forth for a game, over sockets.

I thought the best way would be to have a struct like this:

struct NetMessage
{
public NetMessageType Type;
public byte[] Contents;
}

However, now I'm wondering how to send the data as bytes. I've often
used the BinaryWriter, but can I get the resulting bytes as an array
from it?

In other words, how can I take some base objects, such as strings and
ints, and turn them into an array of bytes without using the
BinaryFormatter?

Well, you can use Encoding.GetBytes, BitConverter etc - but I'd suggest
using a BinaryWriter writing into a MemoryStream, and then call ToArray
on the MemoryStream afterwards.
 
Well, you can use Encoding.GetBytes, BitConverter etc - but I'd suggest
using a BinaryWriter writing into a MemoryStream, and then call ToArray
on the MemoryStream afterwards.

Ah, of course, the memory stream. What a wonderfull thing that is!
 
Back
Top