使用strtoul函数可以方便的把字符串转换成2,8,10,16进致数Convert strings to an unsigned long-integer value. unsigned long strtoul( const char *nptr, char **endptr, int base );Return Valuestrtoul 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.ParametersnptrNull-terminated string to convert endptrPointer to character that stops scanbaseNumber base to use
#include <stdlib.h> #include <stdio.h>void main( void ) { char *string, *stopstring; double x; long l; int base; unsigned long ul; string = "3.1415926This stopped it"; x = strtod( string, &stopstring ); printf( "string = %s\n", string ); printf(" strtod = %f\n", x ); printf(" Stopped scan at: %s\n\n", stopstring ); string = "-10110134932This stopped it"; l = strtol( string, &stopstring, 10 ); printf( "string = %s", string ); printf(" strtol = %ld", l ); printf(" Stopped scan at: %s", stopstring ); string = "10110134932"; printf( "string = %s\n", string ); /* Convert string using base 2, 4, and 8: */ for( base = 2; base <= 8; base *= 2 ) { /* Convert the string: */ ul = strtoul( string, &stopstring, base ); printf( " strtol = %ld (base %d)\n", ul, base ); printf( " Stopped scan at: %s\n", stopstring ); } } 呵呵,从MSDN上来的
sscanf("2A3B","%x",&a);
先将所有的转换为大写的:
length为字符串长度
for(int i=0;i<length;i++)
{
if(ch[i]<'A')
Sum+=(ch[i]-'0')*pow(16,length-1-i);
else
Sum+=(ch[i]-'A'+10)*pow(16,length-1-i);
}
现场编写的,你验证一下,如果正确回个话
unsigned long strtoul( const char *nptr, char **endptr, int base );Return Valuestrtoul 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.ParametersnptrNull-terminated string to convert endptrPointer to character that stops scanbaseNumber base to use
#include <stdio.h>void main( void )
{
char *string, *stopstring;
double x;
long l;
int base;
unsigned long ul;
string = "3.1415926This stopped it";
x = strtod( string, &stopstring );
printf( "string = %s\n", string );
printf(" strtod = %f\n", x );
printf(" Stopped scan at: %s\n\n", stopstring );
string = "-10110134932This stopped it";
l = strtol( string, &stopstring, 10 );
printf( "string = %s", string );
printf(" strtol = %ld", l );
printf(" Stopped scan at: %s", stopstring );
string = "10110134932";
printf( "string = %s\n", string );
/* Convert string using base 2, 4, and 8: */
for( base = 2; base <= 8; base *= 2 )
{
/* Convert the string: */
ul = strtoul( string, &stopstring, base );
printf( " strtol = %ld (base %d)\n", ul, base );
printf( " Stopped scan at: %s\n", stopstring );
}
}
呵呵,从MSDN上来的
高兴,高兴