newbie pointer question.

Go To Last Post
7 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

hi
i need to convert a single character to an integer for which im going to use atoi(). since atoi() takes a pointer as an argument i assume i cant just go

char bar = '9';
uint8_t fu;
fu = atoi(bar);

right?
so do i have to do something like

char bar = '9';
char *bar_ptr;
uint8_t fu;

bar_ptr = &bar;
fu = atoi(bar_ptr);

or can i do something like this:

char bar = '9';
uint8_t fu;

fu = atoi(&bar);

and save ram? i dont have much experience with pointers so im i bit lost...

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The latter (just pass the address to the variable bar). You don't need to create an intermediatry pointer variable in such situations - unless you need to manipulate the address you're better off with addressof ("&") symbols and typecasts where appropriate.

- Dean :twisted:

Make Atmel Studio better with my free extensions. Open source and feedback welcome!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

atoi() needs a string, including the NUL ('\0') terminator, so its argument needs
to be at least 2 bytes. Try:

char bar = '9';
char bar_str[1+1];   // one byte + '\0'

bar_str[0] = bar;
bar_str[1] = '\0';
fu = atoi(bar_str);

For a single char which is known to be (ASCII) numeric, there is a shortcut:

fu = bar - '0';
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

How about just:

char bar[] = {"9"};
fu = atoi(bar);

and if you later need to convert '3' then:

bar[0] = '3';
fu = atoi(bar);

Cliff

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If you like to live life on the edge, then take advantage of the fact that:
1) You only want to convert single-character values, and
2) AVR-GCC treats the AVR as a little-endian machine.

This will work:

uint16_t bar = '9';
fu = atoi((char*)&bar);

*Note* I don't seriously recommend that you use this suggestion!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I know this is a atoi/pointer thread, but if you are only converting single digits, consider this:

ASCII "0" = 00110000 in binary
ASCII "1" = 00110001 in binary
ASCII "9" = 00111001 in binary

Just mask off the upper 4 bits of your ASCII and you have your uint8_t

ucVal = ascVal & 0x0F;

As far as code efficiency goes, I don't hink it can be beat, as far as learning the use of pointers, it is useless.

Last Edited: Fri. Jul 21, 2006 - 12:17 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Someguy22 wrote:
I know this is a atoi/pointer function, but if you are only converting single digits, consider this:

ASCII "0" = 00110000 in binary
ASCII "1" = 00110001 in binary
ASCII "9" = 00111001 in binary

Just mask off the upper 4 bits of your ASCII and you have your uint8_t

thanks thats even better. :D