sprintf或printf的最小实现

时间:2013-05-20 10:15:54

标签: c embedded printf

我正在开发一种速度至关重要的嵌入式DSP,而且内存很短。

目前,sprintf使用我代码中任何函数的大部分资源。我只用它来格式化一些简单的文本:%d, %e, %f, %s,没有任何精确或奇异的操作。

如何实现更适合我用途的基本sprintf或printf函数?

3 个答案:

答案 0 :(得分:11)

这个假定存在一个itoa来转换int到字符表示,并fputs写出一个字符串到你希望它去的地方。

浮点输出至少在一个方面是不符合的:它不会像标准要求那样正确地进行舍入,所以如果你有(例如)内部值1.234存储为1.2399999774,它将打印为1.2399而不是1.2340。这节省了相当多的工作,并且对于大多数典型目的而言仍然足够。

除了您提出的转换之外,这还支持%c%x,但如果您想要删除这些转换,则删除它们非常简单(显然这样做会很明显)保存内存。)

#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>

static void ftoa_fixed(char *buffer, double value);
static void ftoa_sci(char *buffer, double value);

int my_vfprintf(FILE *file, char const *fmt, va_list arg) {

    int int_temp;
    char char_temp;
    char *string_temp;
    double double_temp;

    char ch;
    int length = 0;

    char buffer[512];

    while ( ch = *fmt++) {
        if ( '%' == ch ) {
            switch (ch = *fmt++) {
                /* %% - print out a single %    */
                case '%':
                    fputc('%', file);
                    length++;
                    break;

                /* %c: print out a character    */
                case 'c':
                    char_temp = va_arg(arg, int);
                    fputc(char_temp, file);
                    length++;
                    break;

                /* %s: print out a string       */
                case 's':
                    string_temp = va_arg(arg, char *);
                    fputs(string_temp, file);
                    length += strlen(string_temp);
                    break;

                /* %d: print out an int         */
                case 'd':
                    int_temp = va_arg(arg, int);
                    itoa(int_temp, buffer, 10);
                    fputs(buffer, file);
                    length += strlen(buffer);
                    break;

                /* %x: print out an int in hex  */
                case 'x':
                    int_temp = va_arg(arg, int);
                    itoa(int_temp, buffer, 16);
                    fputs(buffer, file);
                    length += strlen(buffer);
                    break;

                case 'f':
                    double_temp = va_arg(arg, double);
                    ftoa_fixed(buffer, double_temp);
                    fputs(buffer, file);
                    length += strlen(buffer);
                    break;

                case 'e':
                    double_temp = va_arg(arg, double);
                    ftoa_sci(buffer, double_temp);
                    fputs(buffer, file);
                    length += strlen(buffer);
                    break;
            }
        }
        else {
            putc(ch, file);
            length++;
        }
    }
    return length;
}

int normalize(double *val) {
    int exponent = 0;
    double value = *val;

    while (value >= 1.0) {
        value /= 10.0;
        ++exponent;
    }

    while (value < 0.1) {
        value *= 10.0;
        --exponent;
    }
    *val = value;
    return exponent;
}

static void ftoa_fixed(char *buffer, double value) {  
    /* carry out a fixed conversion of a double value to a string, with a precision of 5 decimal digits. 
     * Values with absolute values less than 0.000001 are rounded to 0.0
     * Note: this blindly assumes that the buffer will be large enough to hold the largest possible result.
     * The largest value we expect is an IEEE 754 double precision real, with maximum magnitude of approximately
     * e+308. The C standard requires an implementation to allow a single conversion to produce up to 512 
     * characters, so that's what we really expect as the buffer size.     
     */

    int exponent = 0;
    int places = 0;
    static const int width = 4;

    if (value == 0.0) {
        buffer[0] = '0';
        buffer[1] = '\0';
        return;
    }         

    if (value < 0.0) {
        *buffer++ = '-';
        value = -value;
    }

    exponent = normalize(&value);

    while (exponent > 0) {
        int digit = value * 10;
        *buffer++ = digit + '0';
        value = value * 10 - digit;
        ++places;
        --exponent;
    }

    if (places == 0)
        *buffer++ = '0';

    *buffer++ = '.';

    while (exponent < 0 && places < width) {
        *buffer++ = '0';
        --exponent;
        ++places;
    }

    while (places < width) {
        int digit = value * 10.0;
        *buffer++ = digit + '0';
        value = value * 10.0 - digit;
        ++places;
    }
    *buffer = '\0';
}

void ftoa_sci(char *buffer, double value) {
    int exponent = 0;
    int places = 0;
    static const int width = 4;

    if (value == 0.0) {
        buffer[0] = '0';
        buffer[1] = '\0';
        return;
    }

    if (value < 0.0) {
        *buffer++ = '-';
        value = -value;
    }

    exponent = normalize(&value);

    int digit = value * 10.0;
    *buffer++ = digit + '0';
    value = value * 10.0 - digit;
    --exponent;

    *buffer++ = '.';

    for (int i = 0; i < width; i++) {
        int digit = value * 10.0;
        *buffer++ = digit + '0';
        value = value * 10.0 - digit;
    }

    *buffer++ = 'e';
    itoa(exponent, buffer, 10);
}

int my_printf(char const *fmt, ...) {
    va_list arg;
    int length;

    va_start(arg, fmt);
    length = my_vfprintf(stdout, fmt, arg);
    va_end(arg);
    return length;
}

int my_fprintf(FILE *file, char const *fmt, ...) {
    va_list arg;
    int length;

    va_start(arg, fmt);
    length = my_vfprintf(file, fmt, arg);
    va_end(arg);
    return length;
}


#ifdef TEST 

int main() {

    float floats[] = { 0.0, 1.234e-10, 1.234e+10, -1.234e-10, -1.234e-10 };

    my_printf("%s, %d, %x\n", "Some string", 1, 0x1234);

    for (int i = 0; i < sizeof(floats) / sizeof(floats[0]); i++)
        my_printf("%f, %e\n", floats[i], floats[i]);

    return 0;
}

#endif

答案 1 :(得分:0)

我在这里添加了自己的(v)sprintf实现,但是它不提供浮动支持(这就是为什么我在这里...)。

但是,它实现了说明符csdux以及非标准的b和{ {1}}(二进制和内存十六进制转储);以及标志m01-9*

+

答案 2 :(得分:0)

tl;dr :考虑更小但更完整的 sprintf() 实现。

您可能正在使用的标准库的 sprintf() 实现可能会占用大量资源。但是,您可能可以利用独立的 sprintf() 实现,这样您就可以获得更完整的功能,而无需支付大量内存使用费用。

现在,如果您告诉我们您只需要一些基本功能,为什么要选择它?因为 (s)printf() 使用的本质是我们在进行过程中倾向于使用它的更多方面。你注意到你想打印更大的数字,或者远十进制数字的差异;你想打印一堆值,然后决定你想让它们对齐。或者其他人想使用您添加的打印功能打印您没有想到的东西。

我面临着类似的需求,虽然不是因为资源限制,而是因为标准库不可用……我最终选择了一个名叫 Marco Paland 的人的独立实现,专为低资源设计使用,并且正在修复它,因为它有一堆错误(您不会相信在 sprintf() 中错过极端情况是多么容易)。存储库是 Installation。对于几乎完整的 C99 sprintf 实现和一些额外的(例如二进制值;但不包括 %a 说明符),它大约是 700 LoC。如果你愿意,你可以 ifdef 一些功能 - 有一些定义的控制。

相关问题