把字符串转换为数值的函数,要求支持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);
- 把字符串转换为数值的函数,要求支持16进制
- VC支持十六(16)进制的字符串转换为数值函数strtoul
- 字符串转换为数值函数
- 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
- 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
- 字符串转换为数值
- 字符串转换为数值
- 一个把十六进制字符串转换为十进制数字的函数
- 数值转换为金额格式的函数
- 字符串与数值相互转换的函数
- 字符串与数值相互转换的函数
- 将数值转化为字符串的函数
- 将数值转化为字符串的函数
- 如何把字符转换为对应的数值
- 如何转换字符串为数值- -
- 如何转换字符串为数值- -
- 将字符串转换为数值
- 输入输出--数值转换为字符串
- 查找SQL SERVER日期转换为字符串
- 时间的比较
- 三分钟破解奇迹热门外挂
- MS SQL SERVER中的字符串分割
- 使用js递交面面数据
- 把字符串转换为数值的函数,要求支持16进制
- 佛祖说出的爱情箴言
- 殊途同归 四个程序员的一天
- 鼠标放到图片上,图片慢慢变清淅
- 谈谈我对攻读计算机研究生的看法(转贴)
- 学C++不得不看的一篇文章
- C# 串口读取(事件驱动)
- 30岁开始实现我的程序员梦(ZT)
- 我为什么是最出色的球员(乔丹)