在char数组中插入0x00。
方法一 : 方法一对于短的组码,简单易实现;对于长的组码,稍有不慎就会数错字节数,还很难查出哪个字节出问题
方法二 : 对于短的组码没必要使用方法二,对于长组码,方便组码且不会数错字节数
代码最终实现
char buff[] =
{
0x00,0x00,0x00,0x00,
0x71,0x00,0x00,0x00,
0x03,0x02
}
方法一 (一个一个插入):
对于char *bufffff,0x00自动转化为’\0‘。在函数tttest()中,由于a=0x00,所以看不到char *bufffff的内容。但是char *bufffff和char gggbuff_send[1024]指向的内存是同一块,所以借用bufffff可以实现对char gggbuff_send[1024]的填充。
static int tttest(char *bufffff)//
{
int nRet = 0;
unsigned char a= 0x00;//版本号
unsigned int b= 0x71;
unsigned int c= 0x03;
unsigned int d= 0x02;
char nthreebyte[3];
memset(nthreebyte,0x00,3);
memcpy(bufffff,&a,1);
memcpy(&bufffff[1],nthreebyte,3);
memcpy(&bufffff[4],&b,1);
memcpy(&bufffff[5],nthreebyte,3);
memcpy(&bufffff[8],&c,1);
memcpy(&bufffff[9],&d,1);
return nRet;
}
void main()
{
char gggbuff_send[1024];
tttest(gggbuff_send);
}
方法二(sprintf):
char gbuff_send[1024];
//两个char合成一个hex
//例:0x37 0x31 ---> 0x71
static void format_twochar_to_onehex( char *peer, int peer_len)
{
memset(gbuff_send,0,sizeof (gbuff_send));
char temp[1024];
memset(temp,0,sizeof (temp));
memcpy(temp,peer,peer_len);
for (int i = 0, j = 0 ;i < peer_len; i=i+2,j++)
{
if((peer[i]>= 'a') && (peer[i] <= 'z'))
{
temp[i] = peer[i] -'a' + 0x0a;
}
else
{
temp[i] = peer[i] - 0x30;
}
if((peer[i+1]>= 'a') && (peer[i+1] <= 'z'))
{
temp[i+1] = peer[i+1] -'a'+ 0x0a;
}
else
{
temp[i+1] =peer[i+1] - 0x30;
}
gbuff_send[j] = (temp[i]<<4) + temp[i+1];
}
}
int main()
{
unsigned char a= 0x00;//一个字节
unsigned int b = 0x71;//int占四个字节,0x71占一个字节,其余三个字节为0x00
unsigned char c = 0x00;
unsigned int d = 0x0302;//int占四个字节,0x0302占两个字节,其余两个字节为0x00
sprintf(buff, "%02x%08x%02x%08x",a,b,c,d);
//此时buff为字符‘0’ ‘0’ ‘0’ ‘0‘ ’0‘ ’0‘ ’0‘ ’0‘ ’7‘ ’1‘ ’0‘ ’0‘ ’0‘ ’0‘ ’0‘ ’3‘ ’0‘ ’2‘
//buff即为十六进制的0x30 0x30 0x30 0x30 0x30 0x30 0x30 0x30 0x37 0x31 0x30 0x30 0x30 0x30 0x30 0x30 0x30 0x33 0x30 0x32
//buff按照字符存储,不是想要的格式
//想要的是0x00,0x00,0x00,0x00,0x71,0x00,0x00,0x00,0x03,0x02
memset(gbuff_send,0,1024);
format_twochar_to_onehex(buff,20);//得到gbuff_send即为想得到的格式
return 0;
}