[net.lang.c] Division With Shifts

cottrell@nbs-vms.arpa (COTTRELL, JAMES) (01/09/86)

/*
> Just shifting using an arithmetic shift may give the wrong answer, but
> you could correct the rounding and still get much faster execution like:
> 
> 	shiftRightArithmetic	register
> 	branchIfPositive	label
> 	increment		register
> label:
> 
> so -23/2 = -23>>1 + 1 = 11101001>>2 + 1 = 11110100 + 1 = 11110101 = -11
> which is the right answer...

For -23, but not in the general case. Try an even number. The code must
be like so (for the general shift case):

	Test			Target
	BranchPositive		label
	Add			2**Shiftcount - 1,Target
label:	ShiftRightArithmatic	Target,Shiftcount

So in order to divide by 2, add 1 & shift once; by 4 add three & shift 
twice; by 8 add 7 & shift thrice; etc

> 					-Miles

Miles from nowhere?

	jim		cottrell@nbs
*/
------

chris@umcp-cs.UUCP (Chris Torek) (01/10/86)

I think everyone agrees that for nonnegative integers,
(i >> 1) == (i / 2).  So let us ignore those.  For negative
integers, (i >> 1) tends to round towards -infinity instead
of towards zero.  To fix this all you need to do is add one
before shifting.

I was going to show why, but it hardly seems worth the effort.
It just works.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 4251)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris@umcp-cs		ARPA:	chris@mimsy.umd.edu

ken@gitpyr.UUCP (Ken Hall) (01/10/86)

I want to thank everyone who sent me some code on how to open and write
to a file.

Please forgive me for asking such a simple and elementary question, as many
upbraided me.

Ken Hall