I'm working on some embedded C for a PCB I've developed, but my C is a little rusty!
I'm looking to do some conversions from a char array to various integer types.
First Example:
[input] " 1234" (note the space before the 1)
[convert to] (int16_t) 1234
Second Example:
[input] "-1234"
[convert to] (int16_t) -1234
Third Example:
[input] "2017061234"
[convert to] (uint32_t) 2017061234
I've tried playing around with atoi(), but I don't seem to be getting the result I expected. Any suggestions?
[EDIT]
This is the code for the conversions:
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
A couple of things:
atoi
family of functions since they have no error handling and may crash if the input format is bad. Instead, use the strtol
family of functions.strtol
.Example:
#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);
}
Output:
61176056
3630
-1234
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments