C语言的字符串操做并不像java,Csharp那样提供直接的方法,简单粗暴。因此,在转换的时候每每费力费时,近日作项目正好用到和java程序通信,java发送过来的数据是十六进制数字组成的字符串,解析的时候颇费心思才算完成,因此,权在此作一笔记,方便之后查看,以及须要帮助的童鞋,固然,有问题欢迎随时交流,一同进步,欧耶!~java
1、将数组转换为十六进制同值的字符串数组
读取数组中的数字,打印成字符串的时候以2位大写的格式。app
1 int arrayToStr(unsigned char *buf, unsigned int buflen, char *out) 2 { 3 char strBuf[33] = {0}; 4 char pbuf[32]; 5 int i; 6 for(i = 0; i < buflen; i++) 7 { 8 sprintf(pbuf, "%02X", buf[i]); 9 strncat(strBuf, pbuf, 2); 10 } 11 strncpy(out, strBuf, buflen * 2); 12 printf("out = %s\n", out); 13 return buflen * 2; 14 }
2、将十六进制的字符串转换为十六进制数组ide
下面定义的字符串中的字符只能是0-F的字符,可是不区分大小写的,前面是安装两位为一个数字进行转换,最后一个数字若是仍是两位的则正常转换,若是只剩一位的话则在前面补零输出。spa


1 int StringToHex(char *str, unsigned char *out, unsigned int *outlen) 2 { 3 char *p = str; 4 char high = 0, low = 0; 5 int tmplen = strlen(p), cnt = 0; 6 tmplen = strlen(p); 7 while(cnt < (tmplen / 2)) 8 { 9 high = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48; 10 low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f'))) ? *(p) - 48 - 7 : *(p) - 48; 11 out[cnt] = ((high & 0x0f) << 4 | (low & 0x0f)); 12 p ++; 13 cnt ++; 14 } 15 if(tmplen % 2 != 0) out[cnt] = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48; 16 17 if(outlen != NULL) *outlen = tmplen / 2 + tmplen % 2; 18 return tmplen / 2 + tmplen % 2; 19 }
3、将十进制字符串转化为十进制数组code
1 int StringToCom(char *str, unsigned char *out, int *outlen) 2 { 3 char *p = str; 4 char high = 0, low = 0; 5 int tmplen = strlen(p), cnt = 0; 6 tmplen = strlen(p); 7 if(tmplen % 2 != 0) return -1; 8 while(cnt < tmplen / 2) //1213141516171819 9 { 10 out[cnt] = (*p - 0x30) * 10 + (*(++p) - 0x30); 11 p++; 12 cnt ++; 13 } 14 *outlen = tmplen / 2; 15 return tmplen / 2; 16 }

4、简单的使用方法blog
定义的参数有些为unsigned char,是由于在定义为char的时候,转换为十六进制以后,负数在表示的时候,难看!ip
1 #include "stdio.h" 2 #include "stdlib.h" 3 #include "string.h" 4 5 unsigned char ArrayCom[16] = { 6 11, 12, 13, 14, 15, 16, 17, 18, 7 19, 20, 21, 22, 23, 24, 25, 26}; 8 unsigned char ArrayHex[16] = { 9 0x2c, 0x57, 0x8f, 0x79, 0x27, 0xa9, 0x49, 0xd3, 10 0xb5, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 11 12 char *strHex = "01aa0304050607083f0add0c0d0e0f00"; 13 char *strCom = "1D1213AB6FC1718B19202122232425A6"; 14 15 int main(int argc, const char *argv) 16 { 17 int cnt; 18 char str[33] = {0}; 19 unsigned char out[33]; 20 arrayToStr(ArrayCom, 16, str); 21 22 int outlen = 0; 23 StringToHex(strCom, out, &outlen); 24 for(cnt = 0; cnt < outlen; cnt ++) 25 { 26 printf("%02X ", out[cnt]); 27 } 28 putchar(10); 29 30 return 0; 31 }
