home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / c / 16860 < prev    next >
Encoding:
Internet Message Format  |  1992-11-20  |  1.8 KB

  1. Path: sparky!uunet!olivea!charnel!sifon!thunder.mcrcim.mcgill.edu!mouse
  2. From: mouse@thunder.mcrcim.mcgill.edu (der Mouse)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: converting unsigned int to signed int
  5. Message-ID: <1992Nov20.104109.21538@thunder.mcrcim.mcgill.edu>
  6. Date: 20 Nov 92 10:41:09 GMT
  7. References: <19226@ucdavis.ucdavis.edu>
  8. Organization: McGill Research Centre for Intelligent Machines
  9. Lines: 50
  10.  
  11. In article <19226@ucdavis.ucdavis.edu>, fzjaffe@othello.ucdavis.edu (Rory Jaffe) writes:
  12.  
  13. > What is a safe, portable method of converting from signed int to
  14. > unsigned?
  15.  
  16. A cast.
  17.  
  18. > I want the most negative signed value to convert to 0, and the most
  19. > positive signed value to (max signed int) + abs(max negative signed
  20. > int).
  21.  
  22. This may or may not be possible.  There is no guarantee that signed and
  23. unsigned ints have the same "range", the same number of distinct
  24. possible values.
  25.  
  26. However, given your description, why not just subtract INT_MIN?  That
  27. will come about as close as anything can.  To be fully portable, you
  28. have to split it up into various cases based on the value of the
  29. original integer.  As a sketch, probably full of errors of detail:
  30.  
  31.     #include <limits.h>
  32.     signed int si;
  33.     unsigned int ui;
  34.  
  35.     if (si <= INT_MAX+INT_MIN)
  36.      { ui = si - INT_MIN;
  37.      }
  38. #if INT_MAX+INT_MIN < -1
  39.     /* this can happen only when more than half the possible int
  40.        values are negative - not possible with a two's complement
  41.        binary representation, for example */
  42.     else if (si < 0)
  43.      { /* some code I don't feel like working out */
  44.      }
  45. #endif
  46. #if UINT_MAX < INT_MAX
  47.     /* I'm not sure whether this is allowed; my reference is at
  48.        work and I'm at home */
  49.     else if (s > UINT_MAX)
  50.      { /* more messy code */
  51.      }
  52. #endif
  53.     else
  54.      { ui = (unsigned int)si - (unsigned int)INT_MIN;
  55.      }
  56.  
  57.                     der Mouse
  58.  
  59.                 mouse@larry.mcrcim.mcgill.edu
  60.