Hex String to integer
이전에 포스팅한 GetProfileToString을 통해서, 특정 값을 읽어왔는데 제기럴 Hex 값이었다.
Int 값이었으면 atoi를 이용해서 int로 쓰겠는데 왠걸 hex string... 열심히 구글링 해보니 CodeProject에 Sample이 있어 업어왔다.
linux에서 왜 string.h에 strupr이 없는걸까???????
보안에 문제가 있는 API라서? 쩝....
Set로 움직이는 함수입니다.
꼭 필요한 분들이 있을 것 같습니다.
수정사항이 있으시면 언제든지!!! 피드백 부탁 드립니다.
char* StrUpr( char *str )
{
int loop = 0;
while( str[loop] != '\0' )
{
str[loop] = (char) toupper( str[loop] );
loop++;
}
return str;
}
/*
* hex string to int
*/
int xtoi(char *value)
{
struct CHexMap
{
char chr;
int value;
};
const int HexMapL = 16;
CHexMap HexMap[HexMapL] =
{
{'0', 0}, {'1', 1},
{'2', 2}, {'3', 3},
{'4', 4}, {'5', 5},
{'6', 6}, {'7', 7},
{'8', 8}, {'9', 9},
{'A', 10}, {'B', 11},
{'C', 12}, {'D', 13},
{'E', 14}, {'F', 15}
};
/* remove space */
int len = strlen(value);
for(int i = 0; i < len; i++) {
if( *(value+i) == ' ') {
value++;
} else {
break;
}
}
/* alloc buffer and change upper */
char *mstr = StrUpr(strdup(value));
char *s = mstr;
int result = 0;
if (*s == '0' && *(s + 1) == 'X')
s += 2;
bool firsttime = true;
while (*s != '\0')
{
bool found = false;
for (int i = 0; i < HexMapL; i++)
{
if (*s == HexMap[i].chr)
{
if (!firsttime) result <<= 4;
result |= HexMap[i].value;
found = true;
break;
}
}
if (!found) break;
s++;
firsttime = false;
}
free(mstr);
return result;
}