Search code examples
cintunsigned-integer

Convert unsigned int to signed int C


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

unsigned int x = 65529;
int y = (int) x;

But y is still returning 65529 when it should return -7. Why is that?


Solution

  • 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 <stdint.h>