ESP8266-从字符串中提取数值的函数

由于工作需要,通过WiFi给ESP8266传送字符串数据时,需要提取字符串里面的数值。

比如字符串:"N000000:550,550,550,550,550,1660,550,550,",需要把N000000后面那些数值用一个整型数组存储起来,特此写了以下函数。


宏定义GETDATA_DEBUG是用来打印信息调试用的。

下面函数的具体功能是给string传递一个字符串的首地址(例如:"550,550,550,550,550,1660,550,550,"),给strip传递分隔符(例如英文逗号:‘,'),给resData传递一个数组首地址,resLength是数组长度。执行完毕后,数值就保存到该数组了。


/*
 * 功能:从字符串中提取整型值
 * 参数:
 * 		string:字符串
 * 		strip:分隔符
 * 		resData[]:数据结果
 * 		resLength:resData的数组长度
 */
#define GETDATA_DEBUG	0
bool ICACHE_FLASH_ATTR
getDataFromString(const char *string,const u8 strip, u16 resData[], u16 resLength)
{
	const char *data = string;
	const char *tempStrStart = NULL;
	const char *tempStrEnd = NULL;
	char tempArray[8] = {0};
	u8 tempStrLen = 0;
	u16 tempValue = 0;
	u8 i = 0;
#if GETDATA_DEBUG
	os_printf("\n");
	os_printf("resData Size:%d\n",resLength);
#endif

	do{
#if GETDATA_DEBUG
		os_printf("data:%s\n",data);
#endif
		tempStrStart = data;
		tempStrEnd = os_strchr(tempStrStart, strip);
		if(tempStrEnd == NULL){
			//os_printf("tempStrEnd is NULL!\n");
			break;
		}
		tempStrLen = tempStrEnd - tempStrStart;
		os_strncpy(tempArray, tempStrStart, tempStrLen);
		tempValue = atoi(tempArray);

#if GETDATA_DEBUG
		os_printf("tempStrLen:%d\n",tempStrLen);
		os_printf("tempArray:%s\n", tempArray);
		os_printf("tempValue:%d\n", tempValue);
#endif

		if(i<resLength){
			resData[i] = tempValue;

		}else{
			os_printf("resData is full!\n");
			return false;;
		}

		tempValue = 0;
		os_memset(tempArray, 0, 8);
		data += tempStrLen+1;		//+1跳过逗号
		i++;

	}while(data != NULL || tempValue != 0);

	return true;
}
#undef GETDATA_DEBUG


使用示例:

u16 checkData[16] = {0};
char *data = "550,550,550,550,550,1660,550,550,";
getDataFromString(data, ',', checkData, sizeof(checkData)/sizeof(u16));
os_printf("checkData:%d,%d,%d,%d,%d,%d,%d,%d,\n",
	checkData[0],checkData[1],checkData[2],checkData[3],
	checkData[4],checkData[5],checkData[6],checkData[7]);

该函数修改后可以移植到其他地方。

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值