Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C char* to int conversion

Tags:

c

char

int

How would I go about converting a two-digit number (type char*) to an int?

like image 668
Niek Avatar asked Oct 30 '12 18:10

Niek


People also ask

Can you convert char to int in C?

We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.

What atoi does in C?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.

What is Strtol function in C?

The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.


2 Answers

atoi can do that for you

Example:

char string[] = "1234"; int sum = atoi( string ); printf("Sum = %d\n", sum ); // Outputs: Sum = 1234 
like image 175
Aamir Avatar answered Oct 03 '22 11:10

Aamir


Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s) {   int sign=1;   if(*s == '-'){     sign = -1;     s++;   }   int num=0;   while(*s){     num=((*s)-'0')+num*10;     s++;      }   return num*sign; } 
like image 33
Omkant Avatar answered Oct 03 '22 10:10

Omkant