Path: utzoo!censor!geac!lethe!yunexus!ists!helios.physics.utoronto.ca!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!tut.cis.ohio-state.edu!magnus.ircc.ohio-state.edu!zaphod.mps.ohio-state.edu!rpi!uupsi!sunic!lth.se!newsuser From: magnus%thep.lu.se@Urd.lth.se (Magnus Olsson) Newsgroups: comp.lang.c Subject: Typecasting signed <-> unsigned Keywords: portability question Message-ID: <1991Feb26.093717.21345@lth.se> Date: 26 Feb 91 09:37:17 GMT Article-I.D.: lth.1991Feb26.093717.21345 Sender: newsuser@lth.se (LTH network news server) Reply-To: magnus@thep.lu.se (Magnus Olsson) Organization: Theoretical Physics, Lund university, Sweden Lines: 37 In Turbo C++ on an IBM AT, the following code fragment { unsigned char u,v; signed char s; u = 255; s = (signed char) u; v = (unsigned char) s; } will assign the value -1 to s and 255 to v. This isn't surprising, since these values have the same bit pattern (11111111) on a 2's complement machine. The question is - is this construct portable? I have a suspicion that it will give some other result on a machine that doesn't use 2's complement notation - on a 1's complement machine, for example, the bit pattern 11111111 interpreted as a signed byte is "-0", not -1. Or is the way the conversion should be done specified in the C language (so it's always done the same way)? Perhaps it would be better to write s = (u > 127) ? (int) u - 256 : u; v = (s < 0) ? s + 256 : s; (provided, of course, that one really wants the conversion to be done as under Turbo C++)? Magnus Olsson | \e+ /_ Dept. of Theoretical Physics | \ Z / q University of Lund, Sweden | >----< Internet: magnus@thep.lu.se | / \===== g Bitnet: THEPMO@SELDC52 | /e- \q