将16進制字元串值轉換為 int 整型值
此例中用 "1de" 作為測試字元串,實作代碼如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*
* 将字元轉換為數值
* */
int c2i(char ch)
{
// 如果是數字,則用數字的ASCII碼減去48, 如果ch = '2' ,則 '2' - 48 = 2
if(isdigit(ch))
return ch - 48;
// 如果是字母,但不是A~F,a~f則傳回
if( ch < 'A' || (ch > 'F' && ch < 'a') || ch > 'z' )
return -1;
// 如果是大寫字母,則用數字的ASCII碼減去55, 如果ch = 'A' ,則 'A' - 55 = 10
// 如果是小寫字母,則用數字的ASCII碼減去87, 如果ch = 'a' ,則 'a' - 87 = 10
if(isalpha(ch))
return isupper(ch) ? ch - 55 : ch - 87;
return -1;
}
* 功能:将十六進制字元串轉換為整型(int)數值
int hex2dec(char *hex)
int len;
int num = 0;
int temp;
int bits;
int i;
// 此例中 hex = "1de" 長度為3, hex是main函數傳遞的
len = strlen(hex);
for (i=0, temp=0; i<len; i++, temp=0)
{
// 第一次:i=0, *(hex + i) = *(hex + 0) = '1', 即temp = 1
// 第二次:i=1, *(hex + i) = *(hex + 1) = 'd', 即temp = 13
// 第三次:i=2, *(hex + i) = *(hex + 2) = 'd', 即temp = 14
temp = c2i( *(hex + i) );
// 總共3位,一個16進制位用 4 bit儲存
// 第一次:'1'為最高位,是以temp左移 (len - i -1) * 4 = 2 * 4 = 8 位
// 第二次:'d'為次高位,是以temp左移 (len - i -1) * 4 = 1 * 4 = 4 位
// 第三次:'e'為最低位,是以temp左移 (len - i -1) * 4 = 0 * 4 = 0 位
bits = (len - i - 1) * 4;
temp = temp << bits;
// 此處也可以用 num += temp;進行累加
num = num | temp;
}
// 傳回結果
return num;
int main(int argc, char *argv[])
char ch[10] = {0};
strcpy(ch, "1de");
printf("hex:%d\n", hex2dec(ch));
return 0;
本人在CentOS 6.5下測試
編譯:gcc -Wall test.c -ohex
運作:./hex
輸出:hex:478