Quantcast
Channel: MSP430 Technical Forums
Viewing all articles
Browse latest Browse all 2077

Convert char to integer issue

$
0
0

Hello

 

I am working on a MSP430G2553 project and a strange thing is happening when I am converting two chars to integer.

 

If I only convert one value like this:

char a[2] = {data[9], data[10]};  // Put in a array + terminating NULL byte.
int i_a = (int) atoi(a); // Convert to a integer.

It converts the "a" correctly to a integer, but when I do like this:

char a[2] = {data[9], data[10]};  // Put in a array + terminating NULL byte.
int i_a = (int) atoi(a); // Convert to a integer.

char b[2] = {data[12], data[13]};  // Put in a array + terminating NULL byte.
int i_b = (int) atoi(b); // Convert to a integer.

It converts both "a" and "b" to integer but it adds 1 at the end, for example if "a"="30" after the conversion the "i_a"=301?

 

So this just happens when I convert both "a" and "b". If I remove one of the conversion code it converts the other value correctly...

 

BUT...

 

If I manually add a terminating NULL byte on both "a" and "b" like this:

char a[2] = {data[9], data[10]};  // Put in a array + terminating NULL byte.
a[2] = NULL;
int i_a = (int) atoi(a); // Convert to a integer.

char b[2] = {data[12], data[13]};  // Put in a array + terminating NULL byte.
b[2] = NULL;
int i_b = (int) atoi(b); // Convert to a integer.

it works as intended. Why is this? Shouldn't declaring like "char a[2] = {data[9], data[10]};" autoadd the terminating NULL byte at the end?

 

As you might suspect I am a newbie to this so what is the correct way of doing this?

 

Hope I am clear enough and you understand. Looking forward to a reply.

 

Best regards

Andreas


Viewing all articles
Browse latest Browse all 2077

Trending Articles