Using unsigned with signed int

Discussion in 'General Electronics Chat' started by aamirali, Feb 15, 2013.

  1. aamirali

    Thread Starter Member

    Feb 2, 2012
    415
    1
    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:
    Code ( (Unknown Language)):
    1.  
    2. uint16_t temp;
    3.  int16_t temp2;  
    4. //.........
    5.  
    6.  if(temp2 > 0)
    7.  {    
    8. temp = temp + (uint16_t)temp2;
    9. }
    10.  else
    11. {
    12.  temp2 = -temp2;
    13.   temp = temp - (uint16_t)temp2;
    14. }
    3.Also how to type cast from int to uint. Is it right method to do
    Like :

    Code ( (Unknown Language)):
    1.  
    2. int16_t temp2;
    3.  uint16_t temp;  
    4.  
    5. if(temp2 < 0)       // for safe tytpe casting, will limit -ve range, +ve range is auto  
    6.      temp2 = 0;
    7.  
    8.  
    9.  temp = (uint16_t) (temp2);
    10.  
     
    Last edited by a moderator: Feb 15, 2013
  2. MrChips

    Moderator

    Oct 2, 2009
    12,440
    3,360
    Simple solution = use signed integers = int16_t
     
Loading...