从char数组转换为16bit signed int和32bit unsigned int

时间:2017-06-22 10:15:10

标签: c types embedded string-conversion

我正在为我开发的PCB开发一些嵌入式C,但我的C有点生锈!

我正在寻找从char数组到各种整数类型的转换。

第一个例子:

[input]        " 1234" (note the space before the 1)
[convert to]   (int16_t) 1234

第二个例子:

[input]        "-1234"
[convert to]   (int16_t) -1234

第三个例子:

[input]        "2017061234"
[convert to]   (uint32_t) 2017061234

我尝试过使用atoi(),但我似乎没有得到我期望的结果。有什么建议吗?

[编辑]

这是转化的代码:

char *c_sensor_id = "0061176056";
char *c_reading1 = " 3630";
char *c_reading2 = "-24.30";

uint32_t sensor_id = atoi(c_sensor_id); // comes out as 536880136
uint16_t reading1 = atoi(c_reading1); // comes out as 9224
uint16_t reading2 = atoi(c_reading2); // comes out as 9224

3 个答案:

答案 0 :(得分:2)

有几件事:

  • 从不使用atoi系列函数,因为它们没有错误处理,如果输入格式不好,可能会崩溃。相反,请使用strtol系列函数。
  • 这些功能中的任何一个在资源受限的微控制器上都有点资源。您可能需要推出自己的strtol
  • 版本

示例:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>

int main() 
{
  const char* c_sensor_id = "0061176056";
  const char* c_reading1  = " 3630";
  const char* c_reading2  = "-1234";

  c_reading1++; // fix the weird string format

  uint32_t sensor_id = (uint32_t)strtoul(c_sensor_id, NULL, 10);
  uint16_t reading1  = (uint16_t)strtoul(c_reading1,  NULL, 10);
  int16_t  reading2  = (int16_t) strtol (c_reading2,  NULL, 10);

  printf("%"PRIu32 "\n", sensor_id);
  printf("%"PRIu16 "\n", reading1);
  printf("%"PRId16 "\n", reading2);

}

输出:

61176056
3630
-1234

答案 1 :(得分:1)

观察到的行为非常令人惊讶。我建议编写函数将字符串转换为int32_tuint32_t并使用它们而不是atoi()

uint32_t atou32(const char *s) {
    uint32_t v = 0;
    while (*s == ' ')
        s++;
    while (*s >= '0' && *s <= '9')
        v = v * 10 + *s++ - '0';
    return v;
}

int32_t atos32(const char *s) {
    while (*s == ' ')
        s++;
    return (*s == '-') ? -atou32(s + 1) : atou32(s);
}

没有错误处理,甚至不支持+,但至少将该值转换为32位,如果仅atoi()类型int则不是这种情况在目标平台上有16位。

答案 2 :(得分:-2)

尝试初始化字符串,如下所示:

char c_sensor_id[] = "0061176056";
char c_reading1[] = " 3630";
char c_reading2[] = "-24.30";
相关问题