1. 程式人生 > >十六進制字符串轉十進制整數

十六進制字符串轉十進制整數

n) span turn ostream include ios strlen 表示 argv

十六進制字符串轉十進制整數

編寫一個函數,函數接收一個字符串,是由十六進制數組成的一組字符串,函數的功能是把接到的這組字符串轉換成十進制數字.並將十進制數字返回。

#include <iostream>

using namespace std;

// 十六進制字符串的最大長度
#define MAX_HEX_STR_LEN 100

bool hexToDec(char shex[], int & idec)
{
    size_t i = 0, len = 0;
    int mid = 0;

    len = strlen(shex);
    if (len > MAX_HEX_STR_LEN) {
        
return false; } idec = 0; for (i = 0; i < len; i++) { mid = 0; if (shex[i] >= 0 && shex[i] <= 9) { mid = shex[i] - 0; } else if (shex[i] >= a && shex[i] <= f) { mid = shex[i] - a + 10; } else if
(shex[i] >= A && shex[i] <= F) { mid = shex[i] - A + 10; } else { return false; } // 移位表示變為2的n次方倍 mid <<= ((len - i - 1) << 2); idec += mid; } return true; } int main(int argc, char * argv[]) {
int a = 0; char s[] = "fae3"; hexToDec(s, a); cout << a << endl; return 0; }

十六進制字符串轉十進制整數