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

标签 c++ c formatting arduino long-integer

我正在 Arduino 上开发一个项目,该项目从远程 Web API 解析一些 JSON 数据,并将其显示在 16x2 LCD 上。

我想格式化一个用 TextFinder 解析的 long添加千位分隔符(逗号分隔符即可)。

简而言之,我该如何编写 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++ - 如何在 Arduino 上格式化长加千位分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7104079/

相关文章:

c - 特定情况下的段错误(核心转储)

c++ - CMake add_definitions 不局限于当前目录

android - QVideoFrame::map() 崩溃

c、doug lea 的 malloc——不正确的 free 不会崩溃。为什么?

c - 连接字符串后的 Malloc() 内存损坏错误

java - 有没有办法在 JavaFX 的同一文本行中使用两种不同的字体大小?

java - 将日期格式化为特定格式

java - 我无法将此代码排列在标题下方

c++ - 我需要帮助来理解如何找到代码段的 Big-Oh

c++ - 无法在 C++ lambda 表达式中调用类成员函数