C語言字符串和十六進制的相互轉換方式

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 }
View Code

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 }

 

相關文章
相關標籤/搜索