十六进制字符串转byte (无符号字符串);
方法一:
unsigned char* hexstr_to_char(const char* hexstr) { size_t len = strlen(hexstr); IF_ASSERT(len % 2 != 0) return NULL; size_t final_len = len / 2; unsigned char* chrs = (unsigned char*)malloc((final_len+1) * sizeof(*chrs)); for (size_t i=0, j=0; j<final_len; i+=2, j++) chrs[j] = (hexstr[i] % 32 + 9) % 25 * 16 + (hexstr[i+1] % 32 + 9) % 25; chrs[final_len] = '\0'; return chrs; }
方法二:
int byteArrayToHexString(uint8_t *byte_array, int byte_array_len, char *hexstr, int hexstr_len) { int off = 0; int i; for (i = 0; i < byte_array_len; i ++) { off += snprintf(hexstr + off, hexstr_len - off, "%02x", byte_array[i]); } hexstr[off] = '\0'; return off; }
来源: