Convert unsigned int to signed int C

后端 未结 9 2120
忘掉有多难
忘掉有多难 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条回答
  •  萌比男神i
    2020-12-05 14:58

    It seems like you are expecting int and unsigned int to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting.

    Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases:

    unsigned int x = 65529;
    int y = (short) x;      //  If short is a 16-bit integer.
    

    or alternatively:

    unsigned int x = 65529;
    int y = (int16_t) x;    //  This is defined in 
    

提交回复
热议问题