整数转字符串
char *reverse(char *s)
{
char temp;
char *p = s; //p指向s的头部
char *q = s; //q指向s的尾部
while(*q)
++q;
q--;
//交换移动指针,直到p和q交叉
while(q > p)
{
temp = *p;
*p++ = *q;
*q-- = temp;
}
return s;
}
/*
* 功能:整数转换为字符串
* char s[] 的作用是存储整数的每一位
*/
char *my_itoa(int n)
{
int i = 0,isNegative = 0;
static char s[100]; //必须为static变量,或者是全局变量
if((isNegative = n) < 0) //如果是负数,先转为正数
{
n = -n;
}
do //从各位开始变为字符,直到最高位,最后应该反转
{
s[i++] = n%10 + '0';
n = n/10;
} while(n > 0);
if(isNegative < 0) //如果是负数,补上负号
{
s[i++] = '-';
}
s[i] = '\0'; //最后加上字符串结束符
return reverse(s);
}
调用
char buf1[20];
buf1 = my_itoa(123456);
浮点数转字符串
static char table[]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
void num2char(char *str, double number, uint8_t g, uint8_t l)
{
uint8_t i;
int temp = number/1;
double t2 = 0.0;
for (i = 1; i<=g; i++)
{
if (temp==0)
str[g-i] = table[0];
else
str[g-i] = table[temp%10];
temp = temp/10;
}
*(str+g) = '.';
temp = 0;
t2 = number;
for(i=1; i<=l; i++)
{
temp = t2*10;
str[g+i] = table[temp%10];
t2 = t2*10;
}
*(str+g+l+1) = '\0';
}
int main(int argc, char const *argv[])
{
char str[20];
num2char(str, 23.56821312, 8, 10);
//8是小数点前保留的位数
//10是小数点后保留的位数
return 0;
}
// 结果
00000023.5682131