conversion of short to unsigned it

Ken Turkowski ken at turtlevax.UUCP
Sun Mar 24 07:28:15 AEST 1985


In article <2128 at ncrcae.UUCP> wescott at ncrcae.UUCP (Mike Wescott) writes:
>	unsigned short us;
>	short s;
>	   .
>	   .
>	   .
>	s = -3;
>	us = -3;
>	ui = s;
 ...
>
>	if ((unsigned int)s == us) printf("OOPS\n");
>
>prints OOPS meaning that fffffffd == 0000fffd !!!
>The code generated for the comparison is a
>
>	cmpw	_s, _us
>
>No conversion.  K&R confused me with the "otherwise" phrase
>in the section on arithmetic conversions.  The version of the C standard
>was not much more help but it eventually became clear that the code for
>the comparison is improperly generated.  The short should be sign extend
>and the unsigned short should be padded with 0's on the left and the
>compare should be a cmpl.

I disagree.  The "(unsigned int)" is a cast, saying that s is to be
considered unsigned rather than signed.  It is NOT a conversion.  The
fact that s was declared to be a "short int" is immaterial; it is of
type int rather than float, etc.  This has the same effect as saying
"(unsigned)", without the "int".  Int has no inherent size associated
with it; the size of an int is machine-dependent.  If you want an int
of a specific size, you say "short int" or "long int".

I would suggest that you try the statement

	if ((unsigned long int)s == us) printf("OOPS\n");

instead, and see if you get the same results.  This explicitly
specifies a size conversion.

-- 

Ken Turkowski @ CADLINC, Menlo Park, CA
UUCP: {amd,decwrl,hplabs,nsc,seismo,spar}!turtlevax!ken
ARPA: turtlevax!ken at DECWRL.ARPA



More information about the Comp.lang.c mailing list