当上位机用字符串的形式下发16进制通讯指令给到下位机时的指令解析:
方法一:查表法
size_t charToHex(const char *data, uint8_t *result)
{size_t size = 0;uint8_t i = 0, j = 0, k = 0, n = 0;char listA[] = {"0123456789abcdef"};uint8_t mid[256];for (i = 0; data[i] != '\0'; ++i )for (j = 0; j < 16; ++j)if(data[i] == listA[j])mid[n++] = j;for (k = 0; k < n; ++k)result[k] = (mid[2 * k] * 16 + mid[2 * k + 1]);size = n / 2;return size;
}
int main(void)
{int i = 0;size_t size = 0;uint8_t b[256];while (1){char rxData[256] = {"010300010001fefd,010600020004abcd"};size = charToHex(rxData, b);for (i = 0; i < size; ++i)printf("%02x ", b[i]);printf("\r\n");rt_thread_mdelay(1000);}return RT_EOK;
}
方法二:比较判断
#include "stdio.h"
#include "string.h"int strToHex(const char *str, unsigned int *data)
{int len = 0, n = 0, i = 0;unsigned int mid[256];while(i < strlen(str)){if(str[i] >= '0' && str[i] <= '9')mid[n++] = str[i] - '0';if(str[i] >= 'a' && str[i] <= 'f')mid[n++] = str[i] - 'a' + 10;if(str[i] >= 'A' && str[i] <= 'F')mid[n++] = str[i] - 'A' + 10;i++;}len = n / 2;for(i = 0; i < len; i++)data[i] = mid[2 * i] * 16 + mid[2 * i + 1];return len;
}int main()
{int len = 0;char a[] = {"010300020001cdfd,010600020003bffd,"};unsigned int dat[256];len = strToHex(a,dat);printf("%s\r\n",a);for(int i = 0; i < len; i++)printf("%02x ", dat[i]);printf("\r\n");return 0;
}