C - Character manipulation - Converting a char into an int

We can of course transform a char into an int with the atoi() function.

But what we are going to do now it's to create our own function to transform a string (several char) into a number.

The string passed as the first argument will be our string.
We are going to choose "140" for this example.
To be sure we type a string, we had the double quotes around it.

At the end of the program, we will add 10 to the new number to be sure that all chars has been transformed into an int.
So the string will be transformed into 150.
This string is now, of course an int and not a char * anymore.

Notice that this example works only for value from 0 to 999.
It transform each character (one by one) of the string into an int.
You can improve this tutorial to transform all chars with no limit.
You might then manipulate numbers greater than the maximum value of an unsigned int: 4,294,967,295.

Even the strlen() function has been recoded (easy to do, OK).

The file: main.c

#include <stdio.h>

#include <stdlib.h>


typedef struct t_s

{

  char *nbr;

  int ln_nbr;

  int int_nbr;

} t_t;


int my_strlen(char *str)

{

  int i;


  i = 0;

  while (str[i])

    i++;

  return i;

}


void init_size(t_t *t, char *av[])

{

  t->nbr = av[1];

  t->ln_nbr = my_strlen(t->nbr);

}


void int_creator(t_t *t)

{

  int i;

  int tmp;

  int dec;


  dec = 10;

  tmp = 0;

  t->int_nbr = 0;

  i = 0;

  while (i < t->ln_nbr)

    {

      tmp = (t->nbr[t->ln_nbr - i - 1] - 48);

      if (i == 0)

        t->int_nbr = tmp;

      else

        {

          t->int_nbr += tmp * dec;

          dec *= dec;

        }

      i++;

    }

  printf("int_nbr = %d\n", t->int_nbr);

}


int main(int ac, char *av[])

{

t_t t;


if (ac != 2)

{

printf("Usage: ./exe \"A string\"\n");

exit(1);

}

init_size(&t, av);

int_creator(&t);

t.int_nbr += 10;

printf("t.int_nbr = %d\n", t.int_nbr);

return 0;

}

Let's compile and execute it

$ gcc main.c -o transform ; ./transform "140"

The result

int_nbr = 140

t.int_nbr = 150
So, our char * has been transformed into an int!
 
Of course, you can enter a character as argument.
For example, if you enter "a", you will have 59 as result.
Why?
Because the 'a' character as the value 49 in the ASCII table!
To see this table, on Linux, just type: man ascii on your terminal.
Well done! You made it. laugh

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.