Convert unsigned int to signed int C

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

    I know this is an old question, but I think the responders may have misinterpreted it. I think what was intended was to convert a 16-digit bit sequence received as an unsigned integer (technically, an unsigned short) into a signed integer. This might happen (it recently did to me) when you need to convert something received from a network from network byte order to host byte order. In that case, use a union:

    unsigned short value_from_network;
    unsigned short host_val = ntohs(value_from_network);
    // Now suppose host_val is 65529.
    union SignedUnsigned {
      short          s_int;
      unsigned short us_int;
    };
    SignedUnsigned su;
    su.us_int = host_val;
    short minus_seven = su.s_int;
    

    And now minus_seven has the value -7.

提交回复
热议问题