home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!olivea!charnel!sifon!thunder.mcrcim.mcgill.edu!mouse
- From: mouse@thunder.mcrcim.mcgill.edu (der Mouse)
- Newsgroups: comp.lang.c
- Subject: Re: converting unsigned int to signed int
- Message-ID: <1992Nov20.104109.21538@thunder.mcrcim.mcgill.edu>
- Date: 20 Nov 92 10:41:09 GMT
- References: <19226@ucdavis.ucdavis.edu>
- Organization: McGill Research Centre for Intelligent Machines
- Lines: 50
-
- In article <19226@ucdavis.ucdavis.edu>, fzjaffe@othello.ucdavis.edu (Rory Jaffe) writes:
-
- > What is a safe, portable method of converting from signed int to
- > unsigned?
-
- A cast.
-
- > I want the most negative signed value to convert to 0, and the most
- > positive signed value to (max signed int) + abs(max negative signed
- > int).
-
- This may or may not be possible. There is no guarantee that signed and
- unsigned ints have the same "range", the same number of distinct
- possible values.
-
- However, given your description, why not just subtract INT_MIN? That
- will come about as close as anything can. To be fully portable, you
- have to split it up into various cases based on the value of the
- original integer. As a sketch, probably full of errors of detail:
-
- #include <limits.h>
- signed int si;
- unsigned int ui;
-
- if (si <= INT_MAX+INT_MIN)
- { ui = si - INT_MIN;
- }
- #if INT_MAX+INT_MIN < -1
- /* this can happen only when more than half the possible int
- values are negative - not possible with a two's complement
- binary representation, for example */
- else if (si < 0)
- { /* some code I don't feel like working out */
- }
- #endif
- #if UINT_MAX < INT_MAX
- /* I'm not sure whether this is allowed; my reference is at
- work and I'm at home */
- else if (s > UINT_MAX)
- { /* more messy code */
- }
- #endif
- else
- { ui = (unsigned int)si - (unsigned int)INT_MIN;
- }
-
- der Mouse
-
- mouse@larry.mcrcim.mcgill.edu
-