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,294 of 33,346   
   Seungbeom Kim to All   
   Getting the smallest signed type that ca   
   15 May 12 21:23:50   
   
   From: musiphil@bawi.org   
      
   Hi all,   
      
   The subject explains itself. Let's say you have a pair of objects, a and b,   
   of an unsigned integer type U, and you want to calculate their difference   
   in a signed integer type.   
      
   Obviously you cannot simply write "a - b", because that will yield an   
   unsigned integer value in modulo arithmetic. So you want to write   
      
        S d = static_cast(a) - static_cast(b);   
      
   for a signed integer type S.   
      
   The problem is, how do you determine S? Of course, S should be large enough   
   to represent all the values of U. To be safe, you could just use S=intmax_t   
   for every U, but that might be an overkill; if U=uint16_t, then S=uint32_t   
   is enough, and you don't want to use more expensive arithmetic in uint64_t   
   or uint128_t. So, something like S=int_least[N+1]_t where N=numeric_limits   
   ::digits() would be desirable (+1 because of the sign bit).   
      
   Is there a way to automatically determine S from U?   
      
   --   
   Seungbeom Kim   
      
      
         [ 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