gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:39:24 25 4
gpt4 key购买 nike

我正在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com