how can i combine and store 2 char variables in an integer variable?

advertisements

consider the following data:

char a=12,b=30;
int c=0;

i want the variable c to store the combined value as c=1230. i.e the int datatype has 2bytes,the first byte should hold value of a and the second the value of b. PS: a soln using operators would be great,any other suggestions are also welcome.


You can use bitwise operations as an alternative. A char is guaranteed to be 1 byte, so you can store it by shifting one char then use the operation OR to combine them:

int combine(char c1, char c2) {
    return c1 | c2 << 8;
}

Then you can use AND and a right shift to split them again:

void split(int in, char *c1, char *c2) {
    *c1 = in & 0xff;
    *c2 = in >> 8;
}

This will, however, not give you the output you want but it will store two chars within one int.