有时候的需求比较奇怪,下面直接贴出代码,用到的技术点有两个
1.字符串反转,即交换位置的方法用异或
2.格式化输出,要求每4个字节用"-"隔开
#include
#include
#include
typedef struct _Data
{
char rawData[5][4];
char convertData[30];
}Data;
int main()
{
Data tmp;
unsigned char a[10] = {0x01, 0x02, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77};
unsigned long long c = 0;
unsigned short moduleId = 0;
unsigned char* p1 , *p2;
for(p1 = &a[0], p2 = &a[9]; p2 > p1; p1++, p2 --)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
memcpy(&c, &a[2], 6);
memcpy(&moduleId, &a[0], 2);
printf("[%lld], moduleId=[%d]\n", c, moduleId);
memset(&tmp, 0x0, sizeof(tmp));
sprintf((char*)&tmp.rawData, "%015lld%04d", c, moduleId);
sprintf(tmp.convertData, "%.4s-%.4s-%.4s-%.4s-%.4s",
tmp.rawData[0],
tmp.rawData[1],
tmp.rawData[2],
tmp.rawData[3],
tmp.rawData[4]);
printf("Data=[%s]\n", tmp.convertData);
return 0;
}
最后的sprintf也可以写成:
sprintf(tmp.convertData, "%.*s-%.*s-%.*s-%.*s-%.*s",
sizeof(tmp.rawData[0]), tmp.rawData[0],
sizeof(tmp.rawData[0]), tmp.rawData[1],
sizeof(tmp.rawData[0]), tmp.rawData[2],
sizeof(tmp.rawData[0]), tmp.rawData[3],
sizeof(tmp.rawData[0]), tmp.rawData[4]);