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

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

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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5115100.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存