Convert unsigned int to signed int C

后端 未结 9 2109
忘掉有多难
忘掉有多难 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: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 
       int8_t ibyte;
       uint8_t ubyte;
       int16_t iword;
       //......
    

提交回复
热议问题