printf question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinothg
    New Member
    • Oct 2006
    • 21

    printf question

    Hi,

    Check this program.

    #include <stdio.h>

    int main()
    {
    int x = 0xFFFFFFF0;
    printf("%X\n",x );
    char y = x;
    printf("%X\n", y);
    getchar();
    }


    I have FFFFFFF0 in int variable x and i am assigning it to char. Since a char can hold only 8 bits, it should have only F0. But when i try to print it, it prints the entire content as we had in int.

    If i change the signed char to unsigned char it is working as per expectation. Can any one help me in understanding the underlying conversions.

    If we have a signed char, will the value be stored in 2's complement ?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The int is 32 bits. The largest vaue you can out in there is 0x7FFFFFFF.

    The left bit is reserved for the sign bit and is not part of the data value.

    When the left bit is set (negative) the number is stored in 2's complement.

    Assigning an int to a char (assuming the char is signed) will produce a maximum value of 127 since the left bit is the sign bit again.

    When you use unsigned int and unsigned char, you lose the sign bit which is now part of the value but you also lose the ability to store negative numbers.

    Comment

    Working...