type casting problem

leichter at yale-com.UUCP leichter at yale-com.UUCP
Fri Jun 10 02:43:40 AEST 1983


The only guaranteed way I know of to get a REALLY "unsigned" character is not
to do it at all - rather, step back and look at what you are trying to do and
do it directly.  To look at it simply:

	You want to do:

		a = *cp;

	where cp is a (char *) and a is "unsigned".

	What you REALLY mean is:  Set the bottom 8 bits of a to the 8 bits at
	the location pointed to by cp, and clear the rest of a.  The "right"
	code is then:

		a = (*cp) & 0377.

(I went through this while doing something similar to calculating CRC's - I
was computing a hash function.  Various combinations of unsigned's failed to
get the right result, although I eventually found a way to write it using a
temporary that did the job; I don't remember how, though.  Note that, on an
11 or VAX, a good peephole optimizer OUGHT to recognize that it can avoid the
AND; on a VAX, it can do this assignment directly (convert byte to word, or
whatever); on an 11, it's a CLR followed by a BISB).  I don't know which
compilers are likely to find this; DECUS C, unfortunately, will not (no peep-
hole!).)

BTW:  If you want REAL portability, you are in trouble, since you shouldn't
assume 8-bit bytes.  There is a (small but significant) class of problems, of
which CRC and hashing functions are typical, in which knowing the actual size
of various data objects is essential.  I'd like to see a small but comprehen-
sive set of "machine constants" defined in some known include file for just
such cases.  Things that should be there are:  bits per:  byte, int, etc.;
masks for each (tough to compute at compile time since there is no exponen-
tiation operator); maximum/minimum values in each size object; not to men-
tion the basic floating point quantities (max precision, etc.).  Of course,
you'd still lose out on non-binary machines, but what can you do...
							-- Jerry
						decvax!yale-comix!leichter
							leichter at yale



More information about the Comp.lang.c mailing list