gpt4 book ai didi

c - 如何将一个int转换为一系列字符

转载 作者:行者123 更新时间:2023-12-02 02:34:18 26 4
gpt4 key购买 nike

我正在尝试将 8 位微 Controller (PIC)上的 C 整数分解为其 ASCII 等效字符。

例如:将 982 转换为 '9','8','2'

到目前为止我想出的一切似乎都是蛮力的。这是我现在基本上在做的事情的主要思想:

if( (10 <= n) && (n < 100) ) {
// isolate and update the first order of magnitude
digit_0 = (n % 10);
// isolate and update the second order of magnitude
switch( n - (n % 10) ) {
case 0:
digit_1 = 0;
break;
case 10:
digit_1 = 1;
break;

...

然后我有另一个函数,只需将 0b00110000(48 进制)添加到我的每个数字。

我一直难以找到任何 C 函数来为我做这件事或自己做得很好。

在此先感谢您的帮助!

最佳答案

如果 sprintf 由于某种原因不适合,像这样简单的东西会起作用:

char digits[MAX_DIGITS];
int count = 0;
do {
digits[count++] = n % 10;
n /= 10;
} while (n > 0);

将有 count 个数字,digits[0] 是最不重要的。

关于c - 如何将一个int转换为一系列字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6687486/

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