when storing a large positive integer it is converting to different negative number

后端 未结 1 1488
青春惊慌失措
青春惊慌失措 2021-01-29 11:27

When i storing a large positive integer in unsigned long int in c, then it unknowingly converting to negative number.

for example

 a=2075000020, b=10000         


        
1条回答
  •  日久生厌
    2021-01-29 12:00

    You cannot have been printing an unsigned integer, because it has printed a sign. Even if you declare the variable as unsigned, once it is on the stack for printf() to use, it is interpreted as a binary value to be used as specified by the format in printf().

    Note the difference between these, and the results. In the the third example, you can see that bit 31 is set, which is the sign bit for signed long int.

    #include 
    #include 
    
    int main () {
        unsigned long int a=2075000020, b=100000000, c;
        c = a + b;
        printf ("Signed %ld\n", c);
        printf ("Unsigned %lu\n", c);
        printf ("Hexadecimal 0x%lX\n", c);
        return 0;
    }
    

    Program output:

    Signed -2119967276
    Unsigned 2175000020
    Hexadecimal 0x81A3DDD4
    

    0 讨论(0)
提交回复
热议问题