[C] 纯文本查看 复制代码/**
* 字符串转字节数组
* [url=home.php?mod=space&uid=952169]@Param[/url] source
* 字符串
* @param length
* 字符串长度
* @param target
* 字节数组
* @param n
* 转换后长度
*/
void hex_2_uint8(const char* source, size_t length, uint8_t* target, size_t n) {
n = 0;
for (int i = 0; i < length; i += 2) {
if (source[i] >= 'a' && source[i] <= 'f') {
target[n] = static_cast(source[i] - 'a' + 10);
}
else if (source[i] >= 'A' && source[i] <= 'F') {
target[n] = static_cast(source[i] - 'A' + 10);
}
else {
target[n] = static_cast(source[i] - '0');
}
if (source[i + 1] >= 'a' && source[i + 1] <= 'f') {
target[n] = static_cast((target[n] << 4) | (source[i + 1] - 'a' + 10));
}
else if (source[i + 1] >= 'A' && source[i + 1] <= 'F') {
target[n] = static_cast((target[n] << 4) | (source[i + 1] - 'A' + 10));
}
else {
target[n] = (target[n] << 4) | (source[i + 1] - '0');
}
++n;
}
}
int main() {
const char* keyStr = "7E360165C72B";
uint8_t keya[6] = { 0x7E, 0x36, 0x01, 0x65, 0xC7, 0x2B };
uint8_t test[6];
hex_2_uint8(keyStr, 12, test, 6);
}