博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c语言16进制字符串转字节数组
阅读量:3945 次
发布时间:2019-05-24

本文共 2405 字,大约阅读时间需要 8 分钟。

今天看代码看到两种16进制字符串转字节数组的方法,现贴出来相当于做个笔记了。

第一种:

1 #include
2 #include
3 4 void hex_str_to_byte(char *hex_str, int length, unsigned char *result) 5 {
6 char h, l; 7 for(int i = 0; i < length/2; i++) 8 {
9 if(*hex_str < 58) 10 {
11 h = *hex_str - 48; 12 } 13 else if(*hex_str < 71) 14 {
15 h = *hex_str - 55; 16 } 17 else 18 {
19 h = *hex_str - 87; 20 } 21 hex_str++; 22 if(*hex_str < 58) 23 {
24 l = *hex_str - 48; 25 } 26 else if(*hex_str < 71) 27 {
28 l = *hex_str - 55; 29 } 30 else 31 {
32 l = *hex_str - 87; 33 } 34 hex_str++; 35 *result++ = h<<4|l; 36 } 37 } 38 39 int main() 40 {
41 char *str = "AB32333435363738393a3b3c3d3e3f40"; 42 unsigned char temp[16] = {
0}; 43 hex_str_to_byte(str, strlen("AB32333435363738393a3b3c3d3e3f40"), temp); 44 for (int i = 0; i < 16; i++) 45 {
46 printf("%x ", temp[i]); 47 } 48 printf("\n"); 49 return 0; 50 }

第二种:

36 #include
37 #include
38 #include
39 void hex_str_to_byte(char *in, int len, unsigned char *out) 40 {
41 char *str = (char *)malloc(len); 42 memset(str, 0, len); 43 memcpy(str, in, len); 44 for (int i = 0; i < len; i+=2) 45 {
46 //小写转大写 47 if(str[i] >= 'a' && str[i] <= 'f') str[i] = str[i] - 0x20; 48 if(str[i+1] >= 'a' && str[i] <= 'f') str[i+1] = str[i+1] - 0x20; 49 //处理第前4位 50 if(str[i] >= 'A' && str[i] <= 'F') 51 out[i/2] = (str[i]-'A'+10)<<4; 52 else 53 out[i/2] = (str[i] & ~0x30)<<4; 54 //处理后4位, 并组合起来 55 if(str[i+1] >= 'A' && str[i+1] <= 'F') 56 out[i/2] |= (str[i+1]-'A'+10); 57 else 58 out[i/2] |= (str[i+1] & ~0x30); 59 } 60 free(str); 61 } 62 63 int main() 64 {
65 char *str = "AB32333435363738393a3b3c3d3e3f40"; 66 unsigned char temp[16] = {
0}; 67 hex_str_to_byte(str, strlen("AB32333435363738393a3b3c3d3e3f40"), temp); 68 for (int i = 0; i < 16; i++) 69 {
70 printf("%x ", temp[i]); 71 } 72 printf("\n"); 73 return 0; 74 }

转载地址:http://vqowi.baihongyu.com/

你可能感兴趣的文章
hp DL338服务器修改ilo管理地址
查看>>
vmware convert P2V 错误二三事
查看>>
让kali2020中的zsh有补完功能
查看>>
python解开压缩文件6位纯数字密码
查看>>
5620系列密码清除
查看>>
vncsever-centos&debian
查看>>
华为snmp模板
查看>>
kvm&xen挂载镜像文件
查看>>
SQL Server Union等操作时解决不同数据库字符集冲突的问题
查看>>
Linq GroupJoin(二)
查看>>
递归:访问页面的控件或文件夹的下文件
查看>>
DataGridView分頁控件
查看>>
Linq 使用entity framework查询视图返回重复记录的问题(转)
查看>>
项目中得到执行文件版本或其它信息
查看>>
WinForm DatagridView绑定大量数据卡顿的问题
查看>>
DataGridView或 DataTable导出到excel
查看>>
Ilist To DataTable
查看>>
SQL @@IDENTITY, IDENT_CURRENT,SCOPE_IDENTITY
查看>>
簡單工廠模式
查看>>
SQL Server的數據類型
查看>>