Convert unsigned int to signed int C

后端 未结 9 2121
忘掉有多难
忘掉有多难 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条回答
  •  萌比男神i
    2020-12-05 14:59

    Since converting unsigned values use to represent positive numbers converting it can be done by setting the most significant bit to 0. Therefore a program will not interpret that as a Two`s complement value. One caveat is that this will lose information for numbers that near max of the unsigned type.

    template 
    TSinged UnsignedToSigned(TUnsigned val)
    {
        return val & ~(1 << ((sizeof(TUnsigned) * 8) - 1));
    }
    

提交回复
热议问题