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


C語言的字符串操作並不像java,Csharp那樣提供直接的方法,簡單粗暴。所以,在轉換的時候往往費力費時,近日做項目正好用到和java程序通訊,java發送過來的數據是十六進制數字組成的字符串,解析的時候頗費心思才算完成,所以,權在此做一筆記,方便以后查看,以及需要幫助的童鞋,當然,有問題歡迎隨時交流,一同進步,歐耶!~

一、將數組轉換為十六進制同值的字符串

   讀取數組中的數字,打印成字符串的時候以2位大寫的格式。

 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 }

二、將十六進制的字符串轉換為十六進制數組

下面定義的字符串中的字符只能是0-F的字符,但是不區分大小寫的,前面是安裝兩位為一個數字進行轉換,最后一個數字如果還是兩位的則正常轉換,如果只剩一位的話則在前面補零輸出。

 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

三、將十進制字符串轉化為十進制數組

 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 }

 

四、簡單的使用方法

定義的參數有些為unsigned char,是因為在定義為char的時候,轉換為十六進制之后,負數在表示的時候,難看!

 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM