serialization of primitives to a byte array

A

AndyM

I am trying to figure out how to serialize data over a socket in C#. Every
example I have seen shows sending a string by converting it to a byte array
and then passing to Send(). Simple enough. But how do I convert longs/shorts
etc. to a byte array? How about structs?

I figure I need to somehow serialize it to a stream or something but I'm a
little lost. When I did this stuff in C++ I would just cast the struct to a
void * and pass it.

I would like to have the knowledge to do it by serialization and also via
casting using the unsafe keyword when performance is a concern. Any examples
out there?

here is a test struct I would like to serialize:

[StructLayout(LayoutKind.Sequential, Pack = 1)]

public struct S

{

public ushort m_us;

public ulong m_ul;

public byte m_b;

public ulong m_ul2;

public ushort m_us2;

}

Thanks.
 
M

Mattias Sjögren

Andy,

The BitConverter class can do this. You could also a BinaryWriter to
write them to a network stream.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top