Convert String to an Integer

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Convert String to an Integer

4,635 Views
RoboMan
Contributor I
I was wondering how one would convert a string to an integer.  I see that it doesn't seem codewarrior supports the atoi command.  Thanks in advance.
 
 
Labels (1)
0 Kudos
5 Replies

498 Views
RoboMan
Contributor I
Thanks for the code.  I did find codewarrior has an atoi function, i had just used it incorrectly the first time.  Thanks again.
 
Josh
0 Kudos

498 Views
mudy
Contributor I
If the string represents an hex number you can use this code:
unsigned int atoin(char s[])
{
int i;
unsigned int n;
n = 0;
i=0;

while(s[i]!='\0'){
//for (i = 0; s[i]!='\0'; i++){

if ((s[i] >= '0') && (s[i]  (minor)= '9')){
   n = (16 * n) +(s[i] - '0');}
else{
   n = (16 * n) +(s[i] - 'A' + 10);}
  
i++;
}
return n;
}
mudy
0 Kudos

498 Views
mjbcswitzerland
Specialist V

Hi mudy

The code requires HEX ASCII string to be coded with capitals.
There is a simple trick to make it case independent.

When the character is not between '0' and '9' try this:

n = (16 * n) + ((s[i] - ('a' - '9' - 1)) & 0x0f);

Regards

Mark Butcher
www.mjbc.ch / www.uTasker.com

0 Kudos

498 Views
mudy
Contributor I
Hi mjbcswitzerland!

Thanks!!

regards

mudy
0 Kudos

498 Views
pittbull
Contributor III
Hello,
I don't know if CW has it, but you can code it yourself. It is very simple. Look at this: http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/lib/libc/port/gen/atoi.c
0 Kudos