Topic: CORRECTION Converting int to unsigned int


Author: diamond@jrd.dec.com (Norman Diamond)
Date: 28 Jul 1994 04:17:39 GMT
Raw View
In article <313nj8$do6@news.tuwien.ac.at> hp@vmars.tuwien.ac.at (Peter Holzer) writes:
>However, fwrite and fread are supposed to be able to write arbitrary
>objects to a binary stream and read it back.  Since all stdio I/O
>functions work as if they called fgetc/fputc and fputc converts its
>argument to unsigned char, we can assume that any object can be treated
>as an array of unsigned char without loss of information.

No we can't!  Too bad the other two or three threads involving this
issue aren't also crossposted to comp.std.c++ for their enjoyment.

Suppose char types are 16 bits and int is 16 bits.  Furthermore suppose
that the machine's signed arithmetic uses one's complement.  Now, one's
complement is no problem for unsigned arithmetic and our unsigned chars,
right?  Wrong.  Suppose you stick 0x8000 in an unsigned char and want to
write it.  fputc()'s first argument has type int, so the value gets
demoted to type int in an implementation-defined manner, and the result
must be in the range -32767 to +32767, in an int.  fputc() internally
converts this value back to unsigned char in a standard-defined manner,
and the result is in the range 32769 to 65535 or 0 to 32767; it cannot
possibly be 32768.  So fputc() cannot write the value of 0x8000 correctly.

If fgetc() reads a value of 0x8000, the implementation-defined conversion
to int will yield some int value.  It can have any int value because it
doesn't have to match anything; no call to fputc() could have written it.

Since all stdio I/O functions work as if they called fgetc/fputc, we
cannot assume that any object can be written and read without loss of
information.

I think I know two relatively painless ways to solve the problem:
(1)  Outlaw one's complement implementations; and/or
(2)  Require that INT_MAX be greater than or equal to UCHAR_MAX.

[A few minutes ago I mistakenly wrote:
(2)  Require that INT_MAX be strictly greater than UCHAR_MAX.
Sorry, it is too hard to try to cancel incorrect articles here.]
--
 <<  If this were the company's opinion, I would not be allowed to post it.  >>
segmentation fault (california dumped)