参与公司的web server项目时,在与网页的信息处理中,要将12个字节的字符串例如“012a3b4d5e6f”,转换为十六进制数0x01,0x2a,0x3b,0x4d,0x5e,0x6f
#define uint8_t unsigned char
#define BUILD_UINT8(loByte, hiByte ) \
((uint8_t)(((loByte) & 0x0F) + (((hiByte) & 0x0F) << 4)))
int main()
{
char ID1[12] = "012a3b4c5b6d";
uint8_t mesh_id[6];
uint8_t temp_id[12];
int i;
for(i = 0; i < 12 ; i++) {
if(ID1[i] >= '0' && ID1[i] <= '9') {
temp_id[i] = ID1[i] - '0';
} else {
temp_id[i] = ID1[i] - 'a' + 10;
}
printf(" %d = %d ", i, temp_id[i]);
}
for(i = 0; i < 12 ;) {
mesh_id[i/2] = BUILD_UINT8(temp_id[i+1], temp_id[i]);
i += 2;
}
for(i = 0; i < 6 ; i++) {
printf("%02x\n", mesh_id[i]);
}
return 0;
}