C++ 16진수-10진수 변환

1 개요[ | ]

C++ hex2dec()
C++ 16진수-10진수 변환
#include <iostream> 
using namespace std; 
int main() 
{ 
    cout << stoi("0",     nullptr, 16) << endl;  // 0
    cout << stoi("-a",    nullptr, 16) << endl;  // -10
    cout << stoi("2F",    nullptr, 16) << endl;  // 47
    cout << stoi("-fffe", nullptr, 16) << endl;  // -65534
    cout << stoi("FFFF",  nullptr, 16) << endl;  // 65535
}
#include <iostream> 
using namespace std; 
int hex2dec(string hex) 
{    
    int len = hex.length(); 
    int base = 1; 
    int ret = 0; 
    for (int i=len-1; i>=0; i--) {    
        if (hex[i]>='0' && hex[i]<='9') ret += (hex[i] - 48)*base; 
        else if (hex[i]>='A' && hex[i]<='F') ret += (hex[i] - 55)*base; 
        else if (hex[i]>='a' && hex[i]<='f') ret += (hex[i] - 87)*base; 
        base *= 16; 
    }
    return ret; 
} 
int main() 
{ 
    cout << hex2dec("0")    << endl;  // 0
    cout << hex2dec("a")    << endl;  // 10
    cout << hex2dec("A")    << endl;  // 10
    cout << hex2dec("1A")   << endl;  // 26
    cout << hex2dec("2f")   << endl;  // 47
    cout << hex2dec("ffff") << endl;  // 65535
    cout << hex2dec("FFFF") << endl;  // 65535
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}