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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #include <stdio.h>
    int main()
    {
        char a = 278;
        printf("%d", a);
      
        return 0;
    }

    chevron_right

    
    

    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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #include <stdio.h>
    int main()
    {
        char a = -129;
        printf("%d", a);
      
        return 0;
    }

    chevron_right

    
    

    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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.