Convert unsigned int to signed int C

后端 未结 9 2108
忘掉有多难
忘掉有多难 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:02

    To answer the question posted in the comment above - try something like this:

    unsigned short int x = 65529U;
    short int y = (short int)x;
    
    printf("%d\n", y);
    

    or

    unsigned short int x = 65529U;
    short int y = 0;
    
    memcpy(&y, &x, sizeof(short int);
    printf("%d\n", y);
    
    0 讨论(0)
  • 2020-12-05 15:05

    To understand why, you need to know that the CPU represents signed numbers using the two's complement (maybe not all, but many).

        byte n = 1; //0000 0001 =  1
        n = ~n + 1; //1111 1110 + 0000 0001 = 1111 1111 = -1
    

    And also, that the type int and unsigned int can be of different sized depending on your CPU. When doing specific stuff like this:

       #include <stdint.h>
       int8_t ibyte;
       uint8_t ubyte;
       int16_t iword;
       //......
    
    0 讨论(0)
  • 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.

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