Re: Signed <-> Unsigned conversions.



John Kelly <j...@xxxxxxxxxxxx> wrote:
Charles Sullivan <cwsul...@xxxxxxxxxxxx> wrote:
Is there a C standard for how conversions between signed
and unsigned variables of the same size are implemented.
 E.g., if I have:

 signed   int  s1, s2;
 unsigned int  u1;

 s1 = -100;
 u1 = s1;

at this point u1 = 4294967196

If, and only if UINT_MAX is 4294967295.

 s2 = u1;

which cannot be represented in s2.  Now if you believe
in standards, C99 say:

Otherwise, the new type is signed and the value cannot be
represented in it; either the result is implementation-
defined or an implementation-defined signal is raised.

Please stop quoting non-posted text with > as if it was written
by a previous poster.

N1256 6.3.1.3p2:

"Otherwise, the new type is signed and the value cannot be
represented in it; either the result is implementation-
defined or an implementation-defined signal is raised."

So your program may freak out, or it may give you a
reasonable answer, depending on your compiler
"implementation."

Any implementation-defined result is reasonable since
it was presumably reasonable for compiler writers to
implement it that way.

But you could mention that by far the most common
conversion doesn't involve signals and simply performs
the inverse conversion of signed to unsigned.

 printf("s2 = %d\n", s2);

With my (gcc) compiler, s2 has the same value (-100) as
s1, but I'm wondering if that's a C standard.

It's highly likely on implementations you're ever likely to
see, but it isn't guaranteed. There are still some sign-
magnitude DSP chipsets being designed where the conversion
of unsigned to signed may not be what you might expect.

I'm still waiting for someone to point out an
implementation that raises a signal in this case.

Wait away. You and I may never see one in our lifetimes.
But the fact that a group of people put their money where
their mouth was, personally paying to be 'volunteers' on
the Committee to put this change in place, suggests they
had at least one such actual implementation in mind.

Even without knowing what that implementation is, I dare
you say you're not quite so stunned to know that floating
point signals are not at all uncommon. There have been
implementations of high ranked integers using floating
point representations.

In order to preserve the congruency between signed and
unsigned value bits, it may well be necessary to use a
non-normalised or biased mantissa. I wouldn't find it at
all suprising for such an implementation to raise a
signal rather than go out of its (already convoluted)
way to avoid one.

--
Peter
.