Using unsigned with signed int

Thread Starter

aamirali

Joined Feb 2, 2012
412
I found this :

If an operation involves both signed and unsigned integers, the situation is a bit more complicated. If the unsigned operand is smaller (perhaps we're operating on unsigned int and long int), such that the larger, signed type could represent all values of the smaller, unsigned type, then the unsigned value is converted to the larger, signed type, and the result has the larger, signed type. Otherwise (that is, if the signed type can not represent all values of the unsigned type), both values are converted to a common unsigned type, and the result has that unsigned type.

Few question:
1. It says "if the signed type can not represent all values of the unsigned type), both values are converted to a common unsigned type, and the result has that unsigned type".
So does that mean before result is used, signed in converted to unsigned & then added to form result?
2. I have one problem where I have two same width vars: uint16_t & int16_t
so what I did:
Rich (BB code):
uint16_t temp;
 int16_t temp2;  
//.........

 if(temp2 > 0)
 {    
temp = temp + (uint16_t)temp2; 
} 
 else 
{
 temp2 = -temp2; 
  temp = temp - (uint16_t)temp2; 
}
3.Also how to type cast from int to uint. Is it right method to do
Like :

Rich (BB code):
int16_t temp2;
 uint16_t temp;   

if(temp2 < 0)       // for safe tytpe casting, will limit -ve range, +ve range is auto  
     temp2 = 0;


 temp = (uint16_t) (temp2);
 
Last edited by a moderator:
Top