Converting to a byte array for a socket.send

S

Shreddy

Hi,

I'm trying (or struggling) to convert some C code to C#.

The existing C client is sending a structure via a TCP socket to a network
server. The structure contains a mix of int and char data types [with NO
data alignment i.e. pack(1)].

I can re-create the structure in c# with LayoutKind.Explicit, but how do I
convert this structure to a byte array for use with the Socket.Send()
method?
 
L

Lebesgue

The solution I know of consists of creating a byte array of size of your
structure and using BitConverter class to obtain values of integers and
chars from the struct in the order they are defined. Maybe there's another
possible solution I don't know of, but this one works.

Example:
struct Foo
{
int number;
char c;

public byte[] ToBytes()
{
byte[] numberBytes = BitConverter.GetBytes(number);
byte[] charBytes = BitConverter.GetBytes(c);
byte[] result = new byte[numberBytes.Length + charBytes.Length];
//use Array.Copy to copy contents of both arrays to the result, I
don't know the exact signature off my head
return result;
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

A simple solution would be adding a method like :

public byte[] GetBytes()
{
byte[] buff = new byte[ XXX ] ; //you know the size apriori.
Array.Copy( BitConverter.GetBytes( aInt), buff, 0, 0 , 4 ); // not sure
if this is the correct set of parameters !!!
Array.Copy( BitConverter.GetBytes( aInt), buff, 0, 4 , 4 ); //similar

return buff;
}


Cheers,
 

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