把字符串转换为数值的函数,要求支持16进制

来源:互联网 发布:ecel表格数据有效性 编辑:程序博客网 时间:2024/05/16 09:43

把字符串转为数值型的函数有很多,如atoi(), atol()等,结果一直没找到支持16进制字符串的转换函数。例:把“46BD”转化为无符号整数。

为此自己写了个函数:

//---------------------------------------------------------------------
//
//  Translate string(include A~F in string) to unsigned short.
//  if string length > 4, use the last four char.
// if error, return -1
//

WORD
strToWord( const char * str )
{
 WORD result = 0;
 char buf[4], tempbuf[2];
 int i, j;
 int temp, len;
 
 memset( buf, '0', sizeof( buf ) );
 memset( tempbuf, 0, sizeof( tempbuf ) );

 len = strlen( str );
 if ( len > 0 )
  for ( i = 1; ( i < ( len + 1 ) ) && ( i < 5 ); i++ )
   buf[4-i] = str[len-i];
 else
 {
  result = 0xFFFF;
  return result;
 }
 
 for ( i = 0; i < 4; i++ )
 {
  temp = 0;
  if ( ( buf[i] > 0x2F ) && ( buf[i] < 0x3A ) )
  {
   tempbuf[0] = buf[i];
   temp = atoi( tempbuf );  
   for ( j = i; j < 3; j++)
    temp = temp * 16;
   result = result + temp;
   continue;
  }
  if ( ( buf[i] > 0x40 ) && ( buf[i] < 0x47 ) )
  {
   tempbuf[0] = buf[i] - 0x11;  
   temp = atoi( tempbuf ); 
   temp = temp + 10;
   for ( j = i; j < 3; j++)
    temp = temp * 16;
   result = result + temp;
   continue;
  }
  if ( ( buf[i] > 0x60 ) && ( buf[i] < 0x67 ) )
  {
   tempbuf[0] = buf[i] - 0x31;  
   temp = atoi( tempbuf ); 
   temp = temp + 10;
   for ( j = i; j < 3; j++)
    temp = temp * 16;
   result = result + temp;
   continue;
  }
  result = 0xFFFF;   //the char is not included in 0~9, a~f, A~F, return error.
  return result;
 }
 return result;
}

写完函数后发现有一个很简单的方法实现,太晕了。

用sscanf(const char *buf,const char* format,...);
例如:

char buf[5] = {"3BD"};
long num = 0;
sscanf(buf,"%x",&num);

原创粉丝点击