public byte flag2 = 0;
public ushort uscmd = 0xC664;
public int datalen = 40;
将这几个变量打包成一个 buffer 发送,buffer 数据如下:
flag+flag2+uscmd+datalen
要发送后的格式为byte[]或二进制的,该怎么写?
5 个解决方案
#1
private void button1_Click(object sender, EventArgs e)
{
Data data = new Data();
data.flag = 1;
data.flag2 = 2;
data.uscmd = 66;
data.datalen = 435;
byte[] buffer = new byte[data.Size];
IntPtr ptr = Marshal.AllocHGlobal(data.Size);
Marshal.StructureToPtr(data, ptr, true);
Marshal.Copy(ptr, buffer, 0, buffer.Length);
MessageBox.Show(buffer.Length.ToString());
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Data
{
public byte flag;
public byte flag2;
public ushort uscmd;
public int datalen;
public int Size
{
get { return 8; }
}
}
#2
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
writer.write(flag);
writer.write(flag2);
writer.write(uscmd);
writer.write(datalen);
byte[] buffer = stream.ToArray();
writer.close();
最简单的方法大概如此。。手边没有 Visaul studio。。可能有一些拼写错误。
BinaryWriter writer = new BinaryWriter(stream);
writer.write(flag);
writer.write(flag2);
writer.write(uscmd);
writer.write(datalen);
byte[] buffer = stream.ToArray();
writer.close();
最简单的方法大概如此。。手边没有 Visaul studio。。可能有一些拼写错误。
#3
这个方法合适,性能也比较好,但是要注意Marshal.AllocHGlobal这个分配的内存得手动释放吧
#4
怎么用socket发送啊
#5
查一下socket的send函数声明,应该是3个参数:
IPAddress dest,Byte[] Buffer,SocketOption op.
,第一个参数可能没有如果是tcp的话
首先
connect,然后构造buffer调用send就OK啦,so easy
#1
private void button1_Click(object sender, EventArgs e)
{
Data data = new Data();
data.flag = 1;
data.flag2 = 2;
data.uscmd = 66;
data.datalen = 435;
byte[] buffer = new byte[data.Size];
IntPtr ptr = Marshal.AllocHGlobal(data.Size);
Marshal.StructureToPtr(data, ptr, true);
Marshal.Copy(ptr, buffer, 0, buffer.Length);
MessageBox.Show(buffer.Length.ToString());
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Data
{
public byte flag;
public byte flag2;
public ushort uscmd;
public int datalen;
public int Size
{
get { return 8; }
}
}
#2
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
writer.write(flag);
writer.write(flag2);
writer.write(uscmd);
writer.write(datalen);
byte[] buffer = stream.ToArray();
writer.close();
最简单的方法大概如此。。手边没有 Visaul studio。。可能有一些拼写错误。
BinaryWriter writer = new BinaryWriter(stream);
writer.write(flag);
writer.write(flag2);
writer.write(uscmd);
writer.write(datalen);
byte[] buffer = stream.ToArray();
writer.close();
最简单的方法大概如此。。手边没有 Visaul studio。。可能有一些拼写错误。
#3
这个方法合适,性能也比较好,但是要注意Marshal.AllocHGlobal这个分配的内存得手动释放吧
#4
怎么用socket发送啊
#5
查一下socket的send函数声明,应该是3个参数:
IPAddress dest,Byte[] Buffer,SocketOption op.
,第一个参数可能没有如果是tcp的话
首先
connect,然后构造buffer调用send就OK啦,so easy