[comp.lang.c] Typecasting signed <-> unsigned

magnus%thep.lu.se@Urd.lth.se (Magnus Olsson) (02/26/91)

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