Convert unsigned int to signed int C

后端 未结 9 2114
忘掉有多难
忘掉有多难 2020-12-05 14:31

I am trying to convert 65529 from an unsigned int to a signed int. I tried doing a cast like this:

unsigned int x = 65         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 14:47

    @Mysticial got it. A short is usually 16-bit and will illustrate the answer:

    int main()  
    {
        unsigned int x = 65529;
        int y = (int) x;
        printf("%d\n", y);
    
        unsigned short z = 65529;
        short zz = (short)z;
        printf("%d\n", zz);
    }
    
    65529
    -7
    Press any key to continue . . .
    


    A little more detail. It's all about how signed numbers are stored in memory. Do a search for twos-complement notation for more detail, but here are the basics.

    So let's look at 65529 decimal. It can be represented as FFF9h in hexadecimal. We can also represent that in binary as:

    11111111 11111001

    When we declare short zz = 65529;, the compiler interprets 65529 as a signed value. In twos-complement notation, the top bit signifies whether a signed value is positive or negative. In this case, you can see the top bit is a 1, so it is treated as a negative number. That's why it prints out -7.

    For an unsigned short, we don't care about sign since it's unsigned. So when we print it out using %d, we use all 16 bits, so it's interpreted as 65529.

提交回复
热议问题