integer division in ANSI C

KW Heuer kwh at bentley.UUCP
Fri Mar 7 09:24:28 AEST 1986


In article <1841 at hammer.UUCP> hammer!seifert (Snoopy) writes:
>How about:
>(unsigned) / (unsigned)  generates the positive quotient as fast as possible
>one or both are (signed) generates the correct signed quotient

Won't work.  (unsigned)-1 denotes 65535 (assuming 16-bit ints for simplicity),
so (unsigned)-1 / 2 has to produce the answer 32767.  In order to generate the
correct result for the entire range of unsigned, the VAX compiler has to add
some stupid code (a function call on some compilers), so this can't be used as
the "fastest divide" datatype.

Here's a counterproposal.  Since _int_ has the range [-32768,32767] and
_unsigned_ is [0,65535], add a new datatype _positive_ (or _nonneg_ or
_nosign_) which has the range [0,32767], i.e. the intersection of _int_ and
_unsigned_.  Whenever it encounters an expression of this datatype, the
compiler can assume its sign bit is off and perform whatever optimization
it wants, i.e. use the fastest divide algorithm.  Similarly, ">>" could be
defined as arithmetic shift on _int_, logical shift on _unsigned_, and
fastest shift on _positive_.



More information about the Comp.lang.c mailing list