Open In App

Storage of integer and character values in C

Last Updated : 25 Jul, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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>
    int main()
    {
        char a = 278;
        printf("%d", a);
      
        return 0;
    }

    
    

    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>
    int main()
    {
        char a = -129;
        printf("%d", a);
      
        return 0;
    }

    
    

    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.

Note: The same concept is used to store the integer variables with one difference that the number of bits taken at the end is 16(2 bytes) or 32(4 bytes) bits because the size of int variables is 2 or 4 bytes.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads