参考 (http://eleaction01.spaces.eepw.com.cn/articles/article/item/178168)
int arrayToStr(unsigned char* buf, unsigned int buflen, char* out)
{
char strBuf[33] = { 0 };
char pbuf[32];
int i;
for (i = 0; i < buflen; i++)
{
sprintf(pbuf, "%02X", buf[i]);
strncat(strBuf, pbuf, 2);
}
strncpy(out, strBuf, buflen * 2);
printf("out = %s\n", out);
return buflen * 2;
}
int StringToHex(char* str, unsigned char* out, unsigned int* outlen)
{
char* p = str;
char high = 0, low = 0;
int tmplen = strlen(p), cnt = 0;
tmplen = strlen(p);
while (cnt < (tmplen / 2))
{
high = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
low = (*(++p) > '9' && ((*p <= 'F') || (*p <= 'f'))) ? *(p)-48 - 7 : *(p)-48;
out[cnt] = ((high & 0x0f) << 4 | (low & 0x0f));
p++;
cnt++;
}
if (tmplen % 2 != 0) out[cnt] = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
if (outlen != NULL) *outlen = tmplen / 2 + tmplen % 2;
return tmplen / 2 + tmplen % 2;
}