home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,299 of 33,346   
   Jeremy Todd to All   
   taking abs() of min signed int value   
   16 May 12 10:39:06   
   
   c21e7739   
   From: jeremy@izotope.com   
      
   Hi,   
      
   I need to compute the absolute value of the minimum signed int value   
   for each signed integral type. This value isn't representable as a   
   signed int, but it is representable as an unsigned int.   
      
   This is easy when a larger signed type is available:   
      
   int32_t min_int32 = std::numeric_limits::min();   
   int64_t abs_min_int32= -int64_t(min_int32);   
   uint32_t answer = uint32_t(abs_min_int32);   
      
   I couldn't come up with an elegant solution when attempting this for   
   the 64-bit type. With a two's complement representation, it just so   
   happens that reinterpreting the min signed int as an unsigned value   
   produces the correct result:   
      
   int64_t min_int64 = std::numeric_limits::min();   
   uint64_t answer = uint64_t(min_int64);   
      
   but this felt rather inelegant. Can anyone think of a more elegant   
   solution that does not assume a two's complement binary   
   representation?   
      
   I should note that the standard does not seem to require that   
   abs(min_int) is representable as a uint for a given size, so let's   
   limit our consideration to platforms where it is representable.   
      
   Regards,   
   Jeremy   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca