栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言字符串数字提取函数,支持负数、浮点数、科学记数法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言字符串数字提取函数,支持负数、浮点数、科学记数法

目录
  • 效果
    • 普通数字
    • 小数
    • 科学记数法
  • 源码

平台:
STC89C52
Keil uVision V5.29.0.0
PK51 Prof.Developers Kit Version:9.60.0.0


效果

这里以51单片机为例,对串口接收的字符串中的第三个数进行解码:

普通数字

小数


科学记数法




源码

#ifndef STR2NUM_H_
#define STR2NUM_H_

#include "stdint.h"



extern void str2int(char * str, char flag, int32_t no, int32_t *Output);
extern void str2double(char * str, char flag, int32_t no, double *Output);

#endif 

#include "Str2Num.h"

void str2int(char * str, char flag, int32_t no, int32_t *Output)
{
	int32_t id_end, count, output;
	for (id_end = 0, count = 0; count != no; ++id_end)
	{
		if (str[id_end] == flag || str[id_end] == 'r' || str[id_end] == 'n' || str[id_end] == '')
			++count;
	}
	id_end -= 2;
	for (output = 0, count = 1; str[id_end] != flag && id_end >= 0; --id_end)
	{ 
		if (str[id_end] == '-')
			output *= -1;
		else if (str[id_end] == '+')
			;
		else 
		{
			output += (str[id_end] - '0') * count;
			count *= 10;
		}
	}
	*Output = output;
}

void str2double(char * str, char flag, int32_t no, double *Output)
{
	int32_t id_end, id_dot, id_e, count, id, pow;
	double output;
	for (id_end = 0, count = 0; count != no; ++id_end)
	{
		if (str[id_end] == flag || str[id_end] == 'r' || str[id_end] == 'n' || str[id_end] == '')
			++count;
	}
	id_end -= 2;	//寻找最后一个数字的下标

	for (id_dot = id_end, id_e = -1; str[id_dot] != '.'; --id_dot)
	{
		if (str[id_dot] == 'e' || str[id_dot] == 'E')
			id_e = id_dot;			//标记e的下标
		if (str[id_dot] == flag || str[id_dot] == 'r' || str[id_dot] == 'n' || str[id_dot] == '')
		{
			if(id_e > 0)
				id_dot = id_e;
			else
				id_dot = id_end + 1;	
			break;
		}
	}

	output = 0;
	if (str[id_dot] == '.')
	{
		for (count = 10, id = id_dot + 1; str[id] != flag && str[id] != 'r' && str[id] != 'n' && str[id] != '' && str[id] != 'e' && str[id] != 'E'; ++id)
		{
			output += (str[id] - '0') / (double)count;	//加入小数部分
			count *= 10;
		}
	}

	for (count = 1, id = id_dot - 1; str[id] != flag && id >= 0; --id)
	{
		if (str[id] == '-')
			output *= -1;
		else if (str[id] == '+')
			;
		else
		{
			output += (str[id] - '0') * count;
			count *= 10;								//加入整数部分
		}
	}

	if(id_e > 0)										//指数计算
	{ 
		for (pow = 0, count = 1; id_end != id_e; --id_end)
		{
			if (str[id_end] == '+')
				;
			else if (str[id_end] == '-')
				pow *= -1;
			else 
			{ 
				pow += (str[id_end] - '0') * count;
				count *= 10;
			}
		}
		if (pow > 0)
			while (pow--)
				output *= 10;
		else if(pow < 0)
			while (pow++)
				output /= 10;
	}
	*Output = output;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433299.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号