16进制字符串转字节串
时间: 2023-08-19 21:11:03 浏览: 126
16进制转字符串
要将一个16进制字符串转换成占16字节大小的byte数组,可以使用C语言中的sscanf函数或者strtol函数来实现。下面是两种方法的示例代码:
方法一:使用sscanf函数
```c
unsigned char code\[16\] = {0};
char string\[33\] = "3132333435363738393a3b3c3d3e3f40";
int nLen = strlen(string);
for(int i=0; i<nLen; i+=2) {
sscanf(&string\[i\], "%02X", (unsigned int*)&code\[i/2\]);
}
```
方法二:使用strtol函数
```c
unsigned char code\[16\] = {0};
char string\[33\] = "3132333435363738393a3b3c3d3e3f40";
for(int i=0; i<16; i++) {
char num\[3\] = {0};
sprintf(num, "%c%c", string\[i*2\], string\[i*2+1\]);
code\[i\] = strtol(num, NULL, 16);
}
```
以上两种方法都可以将16进制字符串转换成占16字节大小的byte数组。在这个例子中,输入的16进制字符串是"3132333435363738393a3b3c3d3e3f40",输出的byte数组为\[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40\]。
#### 引用[.reference_title]
- *1* *2* [16进制字符串转字节字节数组](https://blog.csdn.net/weixin_28289089/article/details/117018463)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [16进制字符串转字节](https://blog.csdn.net/csdn_zmf/article/details/122215843)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文