atoi - STM32 atoi 和 strtol 有时会丢失前 2 位数字

标签 atoi stm32 strtol

我正在读取通过 RS485 发送的值,这是编码器的值我首先检查它是否已返回 E 字符(编码器报告错误),如果没有则执行以下操作

    *position = atoi( buffer ); 
    // Also tried *position = (s32) strtol(buffer,NULL,10);

缓冲区中的值是 4033536 并且位置设置为 33536 这不会在这个函数中每次都发生,可能是 1000 次中的 1 次,虽然我没有计算。重新设置程序计数器并在失败时再次执行该行返回相同的结果,但再次启动调试器会导致值正确转换。

我正在使用 keil uvision 4,它是一个使用 stm32f103vet6 和 stm32f10 库 V2.0.1 的定制板,这真的让我感到难过,从来没有遇到过这样的事情,我们将不胜感激。

谢谢

最佳答案

没有人知道我只会发布我最终所做的事情,即编写我自己的转换函数,虽然不理想但它有效。

bool cdec2s32(char* text, s32 *destination)
{
    s32 tempResult = 0;
    char currentChar;
    u8 numDigits = 0;
    bool negative = FALSE;
    bool warning = FALSE;

    if(*text == '-')
    {
      negative = TRUE;
      text++;
    }

while(*text != 0x00 && *text != '\r') //while current character not null or carridge return
{
    numDigits++;
    if(*text >= '0' && *text <= '9')
    {
        currentChar = *text;
        currentChar -= '0';

        if((warning && ((currentChar > 7 && !negative) || currentChar > 8 && negative )) || numDigits > 10) // Check number not too large
        {
            tempResult = 2147483647;
            if(negative)
                tempResult *= -1;

            *destination = tempResult;
            return FALSE;
        }

        tempResult *= 10;
        tempResult += currentChar;
        text++;
        if(numDigits >= 9)
        {
            if(tempResult >= 214748364)
            {
                warning = TRUE; //Need to check next digit as close to limit
            }
        }
    }
    else if(*text == '.' || *text == ',')
    {
        break;
    }
    else
        return FALSE;
}
if(negative)
    tempResult *= -1;

*destination = tempResult;
return TRUE;

关于atoi - STM32 atoi 和 strtol 有时会丢失前 2 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13844233/

相关文章:

不使用 atoi() 或 stoi() 的 C++ 字符串到 int

c - STM32:使用 DMA 时 I2S 输入不工作

c - 带有 LibOpenCM3 的 STM32 FreeRTOS

c - 使用strtol过滤不良命令提示符并打印错误消息(C)

c++ - std::atoll 与 VC++

c - 在 C 中将字符作为整数添加到数组中

c - atoi — 如何识别零和错误之间的区别?

c - stm32f205rg 上的软引导加载程序错误

c++ - strtol 的基础知识?

c - 无法理解 Atoi 函数 - *string - '0'