64,691
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#define YES 1
#define NO 0
int htoi(char s[])
{
int i,n;
int inhex,digital;
i=0;
if (s[i]=='0')
{
i++;
if (s[i]=='x'||s[i]=='X')
{
i++;
}
}
n=0;
inhex=YES;
for(;inhex==YES;i++)
{
if (s[i]>='0'&&s[i]<='9')
digital=s[i]-'0';
else if (s[i]>='a'&&s[i]<='f')
digital=s[i]-'a'+10;
else if (s[i]>='A'&&s[i]<='F')
digital=s[i]-'A'+10;
else
{
inhex=NO;
break;
}
n=16*n+digital;
}
return n;
}
main ()
{
int decimal;
char s[]="0xAA";
decimal=htoi(s);
printf("%d\n",decimal);
}
//用hex函数:
//ios_base& hex ( ios_base& str );
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
long val,n;
char* l_cpTemp = "0x12345678";
istringstream iss;
string strvalues="12345678";
iss.str (l_cpTemp);
iss>>hex>>val;
cout<<val<<endl;
//测试
long u = strtoul(l_cpTemp, 0, 16);
cout<<u<<endl;
return 0;
}
strtoul 函数,可以转换任意进制的
Convert strings to an unsigned long-integer value.
unsigned long strtoul(
const char *nptr,
char **endptr,
int base
);
unsigned long _strtoul_l(
const char *nptr,
char **endptr,
int base,
_locale_t locale
);
unsigned long wcstoul(
const wchar_t *nptr,
wchar_t **endptr,
int base
);
unsigned long _wcstoul_l(
const wchar_t *nptr,
wchar_t **endptr,
int base,
_locale_t locale
);
Parameters
nptr
Null-terminated string to convert.
endptr
Pointer to character that stops scan.
base
Number base to use.
locale
Locale to use.
Return Value
strtoul returns the converted value, if any, or ULONG_MAX on overflow. strtoul returns 0 if no conversion can be performed. wcstoul returns values analogously to strtoul. For both functions, errno is set to ERANGE if overflow or underflow occurs.
See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on this, and other, return codes.
#include "iostream"
using namespace std;
typedef unsigned long ULONG;
int main()
{
char* l_cpTemp = "0x12345678";
ULONG u = strtoul(l_cpTemp, 0, 16);
cout<<u<<endl;
return 0;
}