gpt4 book ai didi

AtmelStudio 中大值的 C strtoul() 错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:37 25 4
gpt4 key购买 nike

我需要将大字符数转换为长字符数,以便在 AtmelStudio 上对我的 Atmega8 芯片进行编程。

我尝试使用 atol()strtoul() 但它不起作用。我在谷歌上看到 strtoul() 有一个错误,它只允许使用较小的值。我试过了,这是真的。我可以使用 strtoul() 将字符“250”转换为长整数,但不能使用“5555”。

我读到修复方法是创建您自己的 strtoul() 函数,但我该怎么做呢?我不知道 strtoul() 的实现,它是库中的一个 extern。

这不起作用:

char *my_time = "2505";      
unsigned long new2 = (unsigned)strtoul(my_time, NULL, 10);

最佳答案

将(无符号)十进制字符串转换为整数的核心是:

unsigned long str2int(const char *s)
{
unsigned long x = 0;
while(isdigit(*s))
{
x *= 10;
x += *s++ - '0';
}
return x;
}

它真的不是很复杂,它只是遍历数字,边走边建立值。 *s++ - '0' 可能是我未能控制我的“经验丰富的 C 程序员的最大简洁综合症”的标志。我也有点着急。更明确的方法可能是:

while(isdigit(*s))
{
x *= 10; /* Each new digit makes the old ones worth more. */
const int digit = *s - '0'; /* Convert digit character to small int. */
x += digit; /* Add the current digit. */
++s;
}

例如,考虑输入 “432”。它将被计算为 ((0 * 10 + 4) * 10 + 3) * 10 + 2。

由于您在 8 位微 Controller 上工作,如果您的应用仅限于 65,536 以下的整数。

关于AtmelStudio 中大值的 C strtoul() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28611259/

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