// Char16ToInt.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std ;
// 含1-9和a-f的16进制字符串转换成int型
int Char16ToInt(const char *cstr)
{
try
{
if (strlen(cstr) > 8)
{
throw "string length error!";
}
char str[9] = {0};
strncpy(str,cstr,8);
int b = 0;
for (int i = strlen(str)-1 ,x = 0; i >= 0 ; i--,x++)
{
if(str[i] >= '0' && str[i] <= '9')
{
b += (str[i] - '0') << (x*4);
}else if(str[i] >= 'a' && str[i] <= 'f')
{
b += (str[i] - 'a' + 10) << (x*4);
}else if(str[i] >= 'A' && str[i] <= 'F')
{
b += (str[i] - 'A' + 10) << (x*4);
}else
{
b = 0;
throw "string error!";
}
}
return b;
}
catch (const char *str)
{
cout << str << endl;
return 0;
}
return 0;
}
int main(int argc, char* argv[])
{
char cstr[] = "1234abcd";
int i = 0;
i = Char16ToInt(cstr);
cout << i << endl;
printf("i = 0x%x\n",i);
return 0;
}