目录
- 效果
- 普通数字
- 小数
- 科学记数法
- 源码
平台:
STC89C52
Keil uVision V5.29.0.0
PK51 Prof.Developers Kit Version:9.60.0.0
效果
这里以51单片机为例,对串口接收的字符串中的第三个数进行解码:
普通数字
小数
科学记数法
源码
/*
* Str2Num.h
*
* Created on: 2021/11/6
* Author: 乙酸氧铍
*/#ifndef STR2NUM_H_
#define STR2NUM_H_#include "stdint.h"/*
str:数字字符串首地址
flag:分隔符
no:第no个数字 从1开始计
Output: 输出结果
*/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 /* STR2NUM_H_ */
/*
* Str2Num.c
*
* Created on: 2021/11/6
* Author: 乙酸氧铍
*/
#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] == '\0')++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] == '\0')++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] == '\0'){if(id_e > 0)id_dot = id_e;elseid_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] != '\0' && 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;
}