首页 > 代码库 > 十六进制字符串转十六进制字节代码
十六进制字符串转十六进制字节代码
/********************************************************************************* * Copyright: (C) 2016 Guo Wenxue<guowenxue@aliyun.com> * All rights reserved. * * Filename: strhex.c * Description: This file used convert HEX string to HEX bytes and write into file * * Version: 1.0.0(09/20/2016) * Author: Guo Wenxue <guowenxue@aliyun.com> * ChangeLog: 1, Release initial version on "09/20/2016 09:16:41 AM" * ********************************************************************************/#include <stdio.h>#include <string.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <errno.h>//#define DEBUG#ifdef DEBUG#define dbg_print(format,args...) printf(format, ##args)#else#define dbg_print(format,args...) do{} while(0);#endifint hexStr2Bytes(char *hexstr, int strlen, unsigned char *bytes){ int i; int cnt = 0; for(i=0; i<strlen; i++) { dbg_print("%c", hexstr[i]); } dbg_print("\n"); for (i=0; i<strlen; i++) { if( !isxdigit(hexstr[i]) ) { continue; } dbg_print("proc ‘%c‘ ", hexstr[i]); if ((hexstr[i] >= ‘0‘) && (hexstr[i] <= ‘9‘)) *bytes = (hexstr[i]-‘0‘) << 4; else *bytes = (toupper(hexstr[i])-‘A‘+10) <<4; dbg_print("[0x%02x] ", *bytes); i++; dbg_print("proc ‘%c‘ ", hexstr[i]); if ((hexstr[i] >= ‘0‘) && (hexstr[i] <= ‘9‘)) *bytes |= hexstr[i]-‘0‘; else *bytes |= toupper(hexstr[i])-‘A‘+10; dbg_print("=>[0x%02x]\n", *bytes); bytes++; cnt ++; } return cnt;}int main (int argc, char **argv){ char *filename; unsigned char buf[1024]; char *hexstr; int bytes; int fd; int i; if(argc != 3 ) { printf("Usage: %s [filename] [hexstr]\n", argv[0]); return -1; } filename = argv[1]; hexstr = argv[2]; if( (fd=open(filename, O_CREAT|O_TRUNC|O_RDWR, 0666)) < 0 ) { printf("Open file ‘%s‘ failure: %s\n", filename, strerror(errno)); return -2; } bytes = hexStr2Bytes(hexstr, strlen(hexstr), buf); write(fd, buf, bytes); close(fd); return 0;}
[guowenxue@centos6 ~]$ ./strhex f1.txt "1B 40 76 4C 4C 93 09 CA 72 8A C2 02 02 02 8A C2
> D2 A2 92 D2 A2 9A 02 02 02 82 8A 82 92 82 8A 8A
> 52 1C 26 1C 2E 1B 69 01 1C 26 C7 EB C7 F3 1C 2E
> 1B 69 00 1B 69 01 30 30 34 1B 69 00 1B 6C 0C 1C
> 26 B0 CB B2 E3 20 20 B9 E3 B2 A5 1C 2E 0D 1B 6C
> 00 0D 0A"
十六进制字符串转十六进制字节代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。