如下一段C++程序:
#define STR1 "ABC"
#define STR2 "\x10\x06\x00\x00\x00\x00\x00\x00"void convstr(){
char msg[256];
memset(msg, 0x00, sizeof(msg));
memcpy(msg,STR1,sizeof(STR1));
memcpy(msg+sizeof(STR1),STR2,sizeof(STR2));
sendto(socket_udp,(char FAR *)msg,sizeof(msg),0,(LPSOCKADDR)&netaddr,nAddrSize);
}如何转为C#程序?
关键是C#中网络发送是用Byte[],怎么把STR1和STR2拼接成一个Byte[],怎么转换啊?
我是Encoding.ASCII.GetBytes试过,出来的跟原先C++发送的包不一样.
解决即送分!
#define STR1 "ABC"
#define STR2 "\x10\x06\x00\x00\x00\x00\x00\x00"void convstr(){
char msg[256];
memset(msg, 0x00, sizeof(msg));
memcpy(msg,STR1,sizeof(STR1));
memcpy(msg+sizeof(STR1),STR2,sizeof(STR2));
sendto(socket_udp,(char FAR *)msg,sizeof(msg),0,(LPSOCKADDR)&netaddr,nAddrSize);
}如何转为C#程序?
关键是C#中网络发送是用Byte[],怎么把STR1和STR2拼接成一个Byte[],怎么转换啊?
我是Encoding.ASCII.GetBytes试过,出来的跟原先C++发送的包不一样.
解决即送分!
STR2 不用转换的,只要转换STR1就好了,你再试试最好把你要发出的正确报文写出来
string STR1="ABC"; byte[] bytesTest = Encoding.UTF8.GetBytes(STR1); string strResult=string.Empty;
string strTemp;
for(int i=0;i<bytesTest.Length;i++)
{
strTemp=System.Convert.ToString(bytesTest[i], 16);
//strTemp=strTemp.Insert(0,new string('0',8-strTemp.Length)); strResult+=strTemp;
}
#define STR2 "\\x10\\x06\\x00\\x00\\x00\\x00\\x00\\x00",结果就是:
ABC\x10\x06\x00\x00\x00\x00\x00\x00
但你最后出来的是string,该用什么方法转成byte[]才是正确的?
//byte[]转为十六进制字符串表示
byte[]bytesTest=new byte[]{16,18,33};stringstrResult=string.Empty;
stringstrTemp;
for(inti=0;i<bytesTest.Length;i++)
{
strTemp=System.Convert.ToString(bytesTest[i], 16);
strTemp=strTemp.Insert(0,new string('0',2-strTemp.Length));strResult+=strTemp;
}
//十六进制字符串转化为byte[]
byte[]bytesTest1=new byte[strResult.Length/2];
for(inti=0;i<bytesTest1.Length;i++)
bytesTest1[i]=Convert.ToByte(strResult.Substring(i*2,2),16);
这是我以前的帖子,你把