0

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?

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
user2311285
  • 437
  • 6
  • 14
  • Many will disagree so I just put it into a comment: http://www.cplusplus.com/reference/cstdlib/atoi/ – Bence Kaulics Oct 18 '16 at 08:12
  • 7
    Using simple math: `int y = ((x[0] - '0') * 10) + (x[1] - '0');` (Note `'0'` means ASCII of digit `0`) – David Ranieri Oct 18 '16 at 08:13
  • 3
    Possible duplicate of [Convert char array to a int number in C](http://stackoverflow.com/questions/10204471/convert-char-array-to-a-int-number-in-c) – Julien Lopez Oct 18 '16 at 08:21
  • 2
    @BenceKaulics because [`atoi` doesn't return any error message](http://stackoverflow.com/q/17710018/995714), [`strtol`](http://stackoverflow.com/q/7021725/995714) is better – phuclv Oct 18 '16 at 08:54

2 Answers2

1

As long as you terminate x with a NULL-terminator you can use atoi.

Example:

#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;
}
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

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.

unwind
  • 391,730
  • 64
  • 469
  • 606