Data Types: Storing character in integer and vice versa with Program

Storage of integer and character values in C

Integer and character variables are used so often in the programs, but how these values are actually stored in C are known to few.Below are a few examples to understand this:

Taking a positive integer value as char:

#include <stdio.h>

intmain()

{

chara = 278;

printf("%d", a);

return0;

}

Output:

22

Explanation:

First, compiler converts 278 from decimal number system to binary number system(100010110) internally and then takes into consideration only the first 8 bits from the right of that number represented in binary and stores this value in the variable a. It will also give warning for overflow.

Taking a negative integer value as char:

#include <stdio.h>

intmain()

{

chara = -129;

printf("%d", a);

return0;

}

Output:

127

Explanation:

First of all, it should be understood that negative numbers are stored in the 2’s complement form of their positive counterpart. The compiler converts 129 from decimal number system to binary number system(10000001) internally, and then, all the zeroes would be changed to one and one to zeroes(i.e. do one’s complement)(01111110) and one would be added to the one’s complement through binary addition to give the two’s complement of that number (01111111). Now, the rightmost 8 bits of the two’s complement would be taken and stored as it is in the variable a. It will also give warning for overflow.