type casting problem

Mark Plotnick mp at mit-eddi.UUCP
Fri Jun 10 12:31:16 AEST 1983


Well, the compiler SHOULD generate code to widen the char to an int
before converting to an unsigned (according to the K&R book).  The
conversion from char to int is done with a cvtbl on the vax and a movb
on the 11, both of which do sign extension (the vax, pdp11, and most
other machines treat chars as signed).  The conversion from int to
unsigned doesn't require any instructions at all.

So it would appear that the VAX compilers are doing the right thing,
but the V7 compiler isn't. 

Notice that I said "SHOULD" in my first sentence.  The V7 compiler
appears to cheat:  if you cast a char into an int and then cast that
into an unsigned, the value is that of the unsigned char (after the
movb, it'll do a bic of the upper 9 bits of the word). That's right, it
ignores the int cast!  This interesting phenomenon is illustrated by
the following program:
main() { 
	register char c = 0377;
	register unsigned int csum;
	int i;

	csum = (unsigned) c;
	printf("%u\n", csum);
	csum = (unsigned)((int) c);
	printf("%u\n", csum);
	csum = (unsigned)(i=(int)c);
	printf("%u\n", csum);
}

You'd THINK that the second and third printf's would both print out the
same thing (actually, you'd expect them ALL to print out the same
thing, and under VAX pcc and VMS C, they do).  With the V7 C compiler
on pdp11's, the output of the program is 255 255 65535.  Sigh.

I don't see a portable solution to your problem. As you said, the V7 C
compiler doesn't know about the unsigned char datatype, and the
conversion rules in K&R don't address how unsigned chars are treated,
anyway.  If anyone has a more up-to-date C reference (book, manual, or
human), please consult them and let us know.

Looks like you'll have to use masking.

	Mark



More information about the Comp.lang.c mailing list