把浮點數轉換成字符串


在C標准庫函數中的sprintf()(位於stdio.h)太大,在STM8上面根本不敢用,動不動就.text overflow,在STM32中運用也太慢。為了將采集的數值通過串口上傳到計算機,只能自己寫了一個浮點數轉換成字符串的函數:

#include <stdio.h>
#include <stdint.h>

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);
    printf("%s\n", str);
    return 0;
}

測試結果如下:

00000023.5682131

轉載自:https://www.cnblogs.com/craftor/p/3820027.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM