[C/C++] 將字串轉成 16 進位

最近在碰嵌入式系統遇到一個還蠻常見的問題,我要將16進位的字串(例如 AAC2) test 轉成16進位的 unsigned int,讓我可以進行 & | not 一些二進位運算,底下是轉換程式,大家參考看看

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int power(int x,int n)
{
    int i;
    int num = 1;
    for(i=1;i<=n;i++)
        num*=x;
    return num;
}

int transfer_string_to_hex(unsigned char *str_name)
{
    char string[]="0123456789ABCDEF";
    int number[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    int i = 0;
    int j = 0;
    int str_number = 0;
    for(i=0; i<sizeof(str_name); i++)
    {
        for(j=0; j<sizeof(string); j++)
        {
            if(toupper(str_name<em></em>) == string[j])
            {
                str_number += power(16, (sizeof(str_name)-1-i))* number[j];
                break;
            }
        }
    }
    return str_number;
}

由於嵌入式並沒有 pow 這個函式可以使用,所以自己寫了 power 來取代,我用在偵測網路線是否有插上:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int detect_wan_wire()
{

    FILE *fp = NULL;
    unsigned char *pch;
    unsigned char buf[128] = {0};
    unsigned int mask = 0x0004;
    int retry = 3;
    int res = 0;
    int i = 0;
    unsigned int a;
    unsigned int b;
    sprintf(buf, "mii_mgr -g -p 7 -r 1 > %s", WAN_FILE);
    system(buf);
    char * pEnd;
    long int li1, li2, li3, li4;
    for (i=0; i<retry; i++)
    {
        if( NULL != (fp = fopen(WAN_FILE , "r")))
        {
            memset (buf , '\0' , sizeof(buf));
            fgets(buf , sizeof ( buf ) , fp);
            pch = strstr(buf, "=") + 2;
            b = transfer_string_to_hex(pch);
            a = b & mask;
            res = (a == 4) ? 1 : 0;
            fclose ( fp );
            fp = NULL;
            memset ( buf , '\0' , sizeof (buf));
        }
    }
    return res;
}

Ref: AND, OR, XOR, NOT 與16 進制


See also