Igor Liferenko - 24 days ago 16
C Question

# How int is converted to char and how char is converted to int?

In the following example the bit representation of byte with all ones is printed:

``````#include <stdio.h>
int main (void)
{
char c = 255;
char z;
for (int i = 7; i >= 0; i--) {
z = 1 << i;
if ((z & c) == z) printf("1"); else printf("0");
}
printf("\n");
return 0;
}
``````

The output is
`11111111`

Now we change
`char c`
to
`int c`
, so that the example becomes:

``````#include <stdio.h>
int main (void)
{
int c = 255;
char z;
for (int i = 7; i >= 0; i--) {
z = 1 << i;
if ((z & c) == z) printf("1"); else printf("0");
}
printf("\n");
return 0;
}
``````

Now the output is
`01111111`
.

Why the output is different?

In the first listing, `(z == c)` tests two char (which are signed by default).

In the second listing, `(z == c)` tests one char and one int, which are both signed by default, but a char set to `1 << 7` is actually set to `-128`, while in an int (at least two bytes) 255 is positive.

To perform operations between a char and an int the compiler expands the char to the size of an int, thus `(int) -128` in this case.

So the test in the 2nd listing

``````if ((z & c) == z)
``````

``````if (((int)(-128) & (int)255) == (int)-128)