Convert unsigned int to signed int C

后端 未结 9 2158
忘掉有多难
忘掉有多难 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 15:08

    The representation of the values 65529u and -7 are identical for 16-bit ints. Only the interpretation of the bits is different.

    For larger ints and these values, you need to sign extend; one way is with logical operations

    int y = (int )(x | 0xffff0000u); // assumes 16 to 32 extension, x is > 32767
    

    If speed is not an issue, or divide is fast on your processor,

    int y = ((int ) (x * 65536u)) / 65536;
    

    The multiply shifts left 16 bits (again, assuming 16 to 32 extension), and the divide shifts right maintaining the sign.

提交回复
热议问题