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?

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;
}

1 Comment

This is C++, the question is about C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.