其他分享
首页 > 其他分享> > c – 如何在Arduino上格式化长添加千位分隔符

c – 如何在Arduino上格式化长添加千位分隔符

作者:互联网

我正在开发一个关于Arduino的项目,它从远程Web API解析一些JSON数据,并在16×2 LCD上显示它.

我想格式化一个长期解析与TextFinder添加千位分隔符(逗号分隔符将没关系).

简而言之,我如何编码formatLong函数?

long longToBeFormatted = 32432423;

formattedLong = formatLong(longToBeFormatted); //How to implement this?

lcd.print(formattedLong) // formattedLong is a string

解决方法:

我不确定在Arduino上使用了什么工具集.有时库会支持非标准的“千位分组”标志 – 单引号字符是典型的扩展名:

printf("%'ld",long_val);

如果您的库不支持此功能,则可能会执行以下操作:

#include <stddef.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <assert.h>

size_t strlcpy( char* dest, char const* src, size_t dest_size);

size_t format_long( long x, char* buf, size_t bufsize)
{
    // This code assumes 32-bit long, is that the
    // case on Arduino?  Modifying it to be able to
    // handle 64-bit longs (or to not care) should be
    // pretty straightforward if that's necessary.

    char scratch[sizeof("-2,147,483,648")];
    char* p = scratch + sizeof(scratch);    // Work from end of buffer
    int neg = (x < 0);

    // Handle a couple special cases
    if (x == 0) {
        return strlcpy( buf, "0", bufsize);
    }
    if (x == INT_MIN) {
        // Lazy way of handling this special case
        return strlcpy( buf, "-2,147,483,648", bufsize);
    }

    // Work with positive values from here on
    if (x < 0) x = -x;

    int group_counter = 3;
    *(--p) = 0; // Null terminate the scratch buffer

    while (x != 0) {
        int digit = x % 10;
        x = x / 10;

        assert( p != &scratch[0]);
        *(--p) = "0123456789"[digit];

        if ((x != 0) && (--group_counter == 0)) {
            assert( p != &scratch[0]);
            *(--p) = ',';
            group_counter = 3;
        }
    }

    if (neg) {
        assert( p != &scratch[0]);
        *(--p) = '-';
    }
    return strlcpy(buf, p, bufsize);
}


/*
    A non-optimal strlcpy() implementation that helps copying string
    without danger of buffer overflow.

    This is provided just in case you don't have an implementation
    so the code above will actually compile and run.
*/
size_t strlcpy( char* dest, char const* src, size_t dest_size)
{
    size_t len = strlen(src);

    if (dest_size == 0) {
        // nothing to copy - just return how long the buffer should be
        //  (note that the return value doens't include the null terminator)
        return len;
    }

    size_t tocopy = (dest_size <= len) ? dest_size-1 : len;

    memmove( dest, src, tocopy);
    dest[tocopy] = 0;

    return len;
}

标签:c-3,c,long-integer,arduino,formatting
来源: https://codeday.me/bug/20190903/1795124.html