將16進制字符串值轉換為 int 整型值
阿新 • • 發佈:2019-02-15
har 大寫字母 i++ for 值轉換 轉換 num 小寫字母 bits
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 hex2dec(const 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 aa;
char temp2[11] = "12b";
aa = hex2dec(temp2);
將16進制字符串值轉換為 int 整型值