Say I have,
char x[0] = '1';
char x[1] = '2';
I need to 'concatenate' these two into an integer variable,
int y = 12;
How do I do this?
Say I have,
char x[0] = '1';
char x[1] = '2';
I need to 'concatenate' these two into an integer variable,
int y = 12;
How do I do this?
As long as you terminate x
with a NULL-terminator you can use atoi
.
#include <stdlib.h>
#include <stdio.h>
int main() {
char x[3];
x[0] = '1';
x[1] = '2';
x[2] = '\0';
int x_int = atoi(x);
printf("%i", x_int);
return 0;
}
The simplest way, if it's really only two digits and you don't want to "go up" (in complexity) to a string in order to use string-conversion functions, is to just compute it directly using the basic structure of a number. Each digit is worth 10 times more than the one to its right.
const char x[2] = { '1', '2' };
const int value = 10 * (x[0] - '0') + (x[1] - '0');
This will set value
to 12
by computing 10 * 1 + 2
.
The subtraction of 0
, meaning "the numerical value of the digit zero in the target's character encoding", works since C requires the decimal digits to be encoded in sequence.